交集 table 的连接语句
Join statement for intersection table
我想将用户连接到一辆或多辆汽车。表格如下所示:
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
哪个是正确的 select 语句,结果如下:
- tom 有 car1 和 2
- max 有 car1
我无法使用 INNER JOIN
.. 正确的说法是什么?
我想你想要 join
s 和聚合:
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;
你需要两个加入
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
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:您也可以在没有任何连接的情况下执行此操作,在某些情况下,它更快更干净。
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
在这种情况下,DESCRIBE 显示了相同的结果,因此任一选项都适合您。
您必须加入表,按名称分组并使用 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 |
我想将用户连接到一辆或多辆汽车。表格如下所示:
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
哪个是正确的 select 语句,结果如下:
- tom 有 car1 和 2
- max 有 car1
我无法使用 INNER JOIN
.. 正确的说法是什么?
我想你想要 join
s 和聚合:
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;
你需要两个加入
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
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:您也可以在没有任何连接的情况下执行此操作,在某些情况下,它更快更干净。
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
在这种情况下,DESCRIBE 显示了相同的结果,因此任一选项都适合您。
您必须加入表,按名称分组并使用 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 |