相交表的联接语句

问题描述 投票:0回答:4

我想将用户连接到一辆或多辆汽车。表格如下:

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

哪个是正确的选择语句,以便结果像是tom具有car1和2而max具有car1?我无法将其与INNER JOIN一起使用。正确的陈述是什么?

php mysql sql join intersection
4个回答
1
投票
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

0
投票

我认为您需要join和汇总:

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;

0
投票

您需要两个联接

  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

0
投票

您必须加入表,按名称分组并使用group_concat()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

请参见demo。结果:

| col                   |
| --------------------- |
| tom has car1 and car2 |
| max has car1          |
热门问题
推荐问题
最新问题