简体   繁体   English

用一个SQL查询连接三个表

[英]Connect three tables with a single SQL-Query

If I have this three tables: 如果我有这三个表:

table1: id, title, content
connection: id_t1, id_t2
table2: id, title, content

In my case I just select a single row of table1. 在我来说,我只选择table1的排。 For this result there are many rows in table2. 为此,表2中有很多行。 The connection of both tables can be found in the table 'connection' 可以在表“连接”中找到两个表的连接

How do I have to create the query to get this result? 我如何创建查询才能获得此结果?

table1-title
table2-content1
table2-content2
table2-content3
table1-content

If I understand correctly I believe you want to use GROUP BY with the GROUP_CONCAT function 如果我理解正确,我相信您想将GROUP BY与GROUP_CONCAT函数一起使用
The query would look something like this: 查询如下所示:

SELECT table1.title, GROUP_CONCAT(table2.content) as table2.group_content, table1.content
FROM table1
JOIN connection on table1.id = id_t1
JOIN table2 on connection.id_t2 = table2.id
GROUP BY table2.content

This would give you one row for each table1.id, with multiple table2.content rows concatenated into one column (called table2.group_content in this example). 这将为您每个table1.id提供一行,并将多个table2.content行串联成一列(在此示例中称为table2.group_content)。

select title from table1 where title_id = 1
UNION
select t2.content 
from table2 t2, table1 t1, connection c  
where t1.title_id = 1
    and t1.title_id = c.id_t1
    and c.id_t2 = t2.title_id
UNION
select content from table1 where title_id = 1

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

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