MySQL一对多关系单一查询

时间:2016-09-15 05:03:09

标签: mysql

我有这两张桌子。我会尽量简单:

Sample value in main_table:
id = 1

Sample value in details_table:
id = 1
type = book
name = harry potter

id = 1
type = paper
name = post it

我需要的结果是获取这两种类型的名称的id。

id    book            paper
1     harry potter    post it

这甚至可能吗?

2 个答案:

答案 0 :(得分:2)

只需加入详细信息表两次:

Select m.id, d1.name as book, d2.name as paper from main_table m 
join Details_table d1 on m.id =d1.id and d1.type = 'book'
join Details_table d2 on m.id =d2.id and d2.type = 'paper'

答案 1 :(得分:1)

您的预期输出表明您希望透视type并根据其值生成列。假设可以显示的唯一类型是bookpaper,则以下查询应该有效:

SELECT t2.id,
       MAX(CASE WHEN t2.type = 'book'  THEN name ELSE NULL END) AS book,
       MAX(CASE WHEN t2.type = 'paper' THEN name ELSE NULL END) AS paper
FROM main_table t1
INNER JOIN details_table t2
    ON t1.id = t2.id
GROUP BY t2.id

在这里演示:

SQLFiddle