MySQL如何查询复杂的关系表

时间:2014-01-07 09:14:15

标签: mysql sql

我有这张表:

enter image description here

我想展示一篇文章,其主题相关术语是“牛奶”。

subject_catalog表字典:

index_key = primary key
subject = takes any words
rt_key = serves as 'related term' foreign key to its own.

subject_catalog的样本数据:

|index_key|subject|rt_key|
|------------------------|
|  1      | tea   | null |
|  2      | milk  | 1    |
|------------------------|

文章的样本数据:

|article_key|title     |pages|
|----------------------------|
|  1        | article_1| 5   |
|  2        | article_2| 3   |
|----------------------------|

article_subject的示例数据:

|article_key|index_key|
|---------------------|
|  1        | 1       |
|---------------------|

这是我的试用查询,但它不会显示任何文章:

SELECT
    `article`.`title`
FROM
    `article_subject`
    INNER JOIN `article` 
        ON (`article_subject`.`article_key` = `article`.`article_key`)
    INNER JOIN `subject_catalog` 
        ON (`article_subject`.`index_key` = `subject_catalog`.`index_key`)
    INNER JOIN `subject_catalog` AS `subject_catalog_1` 
        ON (`subject_catalog_1`.`rt_key` = `subject_catalog`.`index_key`)
WHERE `subject_catalog_1`.`subject` LIKE 'milk%'

2 个答案:

答案 0 :(得分:2)

试试这个

SELECT article.title
FROM article_subject
    LEFT JOIN article USING (article_key)
    LEFT JOIN subject_catalog USING (index_key)
    LEFT JOIN subject_catalog sc2 ON subject_catalog.index_key = sc2.rt_key
WHERE subject_catalog.subject LIKE 'milk%' OR sc2.subject LIKE 'milk%'

http://sqlfiddle.com/#!2/7d5f5/3/0

答案 1 :(得分:0)

Select A.title from article A inner Join article_subject S 
On A.article_key =S.article_key inner join subject_catalog C 
on C.index_key = C.index_key where C.rt_key =1

SQLFIDDLE

相关问题