简体   繁体   English

MySQL一对多关系单查询

[英]MySQL one-to-many relationship single query

I have this two tables. 我有这两个表。 I'll make it as simple as possible: 我将使其尽可能简单:

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

The result I need is to get id with the name for those two types. 我需要的结果是使用这两种类型的名称获取ID。

id    book            paper
1     harry potter    post it

Is this even possible? 这有可能吗?

Simply join the details table twice: 只需将详细信息表连接两次:

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'

Your expected output suggests that you want to pivot the type and generate columns based on its value. 预期的输出表明您希望透视该type并根据其值生成列。 Assuming the only types which can appear are book and paper , then the following query should work: 假设可以出现的唯一类型是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

Demo here: 演示在这里:

SQLFiddle SQLFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM