开发者

MySQL JOIN based on dynamic LIKE statement between multiple tables

I have a table called faq. This table consists from fields faq_id,faq_subject. I have another table called article which consists of article_id,ticket_id,a_body and which stores articles in a specific ticket. Naturally there is also a table "ticket" with fields ticket_id,ticket_number.

I want to retrieve a result table in format: ticket_number,faq_id,faq_subject.

In order to do this I need to sear开发者_JAVA技巧ch for faq_id in the article.a_body field using %LIKE% statement.

My question is, how can I do this dynamically such that I return with SQL one result table, which is in format ticket_number,faq_id,faq_subject.

I tried multiple configurations of UNION ALL, LEFT JOIN, LEFT OUTER JOIN statements, but they all return either too many rows, or have different problems.

Is this even possible with MySQL, and is it possible to write an SQL statement which includes @variables and can take care of this?


First off, that kind of a design is problematic. You have certain data embedded within another column, which is going to cause logic as well as performance problems (since you can't index the a_body in such a way that it will help the JOIN). If this is a one-time thing then that's one issue, but otherwise you're going to have problems with this design.

Second, consider this example: You're searching for faq_id #123. You have an article that includes faq_id 4123. You're going to end up with a false match there. You can embed the faq_id values in the text with some sort of mark-up (for example, [faq_id:123]), but at that point you might as well be saving them off in another table as well.

The following query should work (I think that MySQL supports CAST, if not then you might need to adjust that).

SELECT
    T.ticket_number,
    F.faq_id,
    F.faq_subject
FROM
    Articles A
INNER JOIN FAQs F ON
    A.a_body LIKE CONCAT('%', F.faq_id, '%')
INNER JOIN Tickets T ON
    T.ticket_id = A.ticket_id

EDIT: Corrected to use CONCAT


SELECT DISTINCT t.ticket_number, f.faq_id, f.faq_subject
FROM faq.f
INNER JOIN article a ON (a.a_body RLIKE CONCAT('faq_id: ',faq_id))
INNER JOIN ticket t ON (t.ticket_id = a.ticket_id)
WHERE somecriteria
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜