简体   繁体   中英

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. For this result there are many rows in table2. 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
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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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