简体   繁体   中英

Join statement for intersection table

I'd like to connect a user to one or multiple cars. The tables look like this:

table_a

id     name
1      tom
2      max

table_b

id     car
1      car1
2      car2
3      car3

table_ab

id     id_a     id_b
1      1        1
2      1        2
3      2        1

Which is the correct select statement so that the result is like:

  • tom has car1 and 2
  • max has car1

I don't get it to work with INNER JOIN .. what is the correct statement?

SELECT `name`,`car` FROM table_a a
INNER JOIN table_ab ab ON a.id = ab.id_a
INNER JOIN table_b b ON ab.id_b = b.id

PS: You can also do this without any joins, in some cases, its faster and cleaner.

SELECT `name`,`car` FROM table_a a,table_b b, table_ab ab
WHERE a.id = ab.id_a AND ab.id_b = b.id

In this case, DESCRIBE showed identical results, so either options will work for you.

I think you want join s and aggregation:

select a.name, group_concat(car) as cars
from ab join
     a
     on a.id = ab.id_a join
     b
     on b.id = ab.id_b
group by a.id, a.name;

You need two join

  select a.name, b.car
  from table_ab ab
  inner join  table_a a ON a.id = ab.id_a
  inner join  table_b b ON b.id = ab.id_b

You must join the tables, group by name and use group_concat() combined with concat() :

select concat(a.name, ' has ', group_concat(car separator ' and ')) col
from table_a a 
inner join table_ab ab on ab.id_a = a.id
inner join table_b b on ab.id_b = b.id
group by a.id, a.name

See the demo .
Results:

| col                   |
| --------------------- |
| tom has car1 and car2 |
| max has car1          |

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