这里有三个表:
a 表
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
b 表
+----+------+------+
| id | a_id | c_id |
+----+------+------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
| 4 | 2 | 3 |
| 5 | 3 | 1 |
| 6 | 3 | 3 |
+----+------+------+
c 表
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
b 表 关联了 a 表 和 c 表
查询全表时:
SELECT a.id, group_concat(c.id)
FROM a
LEFT JOIN b ON b.a_id = a.id
LEFT JOIN c ON c.id = b.c_id
GROUP BY a.id;
+----+--------------------+
| id | group_concat(c.id) |
+----+--------------------+
| 1 | 1,2 |
| 2 | 2,3 |
| 3 | 1,3 |
+----+--------------------+
然后有条件: where c.id
= 2
我想要的:
+----+--------------------+
| id | group_concat(c.id) |
+----+--------------------+
| 1 | 1,2 |
| 2 | 2,3 |
+----+--------------------+
然而结果是:
+----+--------------------+
| id | group_concat(c.id) |
+----+--------------------+
| 1 | 2 |
| 2 | 2 |
+----+--------------------+
如何写 查询条件?
源氏大雕
结果:
先倒过来筛选出 符合条件的 a表 再查询
SELECT a1.id, group_concat(c.id)
FROM
(
SELECT a.id
FROM a
LEFT JOIN b ON b.a_id = a.id
LEFT JOIN c ON c.id = b.c_id
WHERE c.id = 2
)
AS a1 #筛选出的a表
LEFT JOIN b ON b.a_id = a1.id
LEFT JOIN c ON c.id = b.c_id
GROUP BY a1.id
还有其他答案吗
1
noNOno 2017-03-06 18:22:04 +08:00
b.c_id=2
|
2
1010011010 OP @noNOno #1
一样的。 |
3
noNOno 2017-03-06 18:28:32 +08:00
@1010011010 不连 a 表应该就对了,我在脑补...
|
4
zeraba 2017-03-06 18:55:42 +08:00 via Android
|
5
1010011010 OP |
6
zeraba 2017-03-06 20:50:49 +08:00
@1010011010
''' SELECT b.a_id, group_concat(b.c_id) FROM (SELECT a_id FROM b WHERE c_id = 2) t1 LEFT JOIN b ON t1.a_id = b.a_id LEFT JOIN c ON c.id = b.c_id GROUP BY b.a_id; 理论上更优?本来要打这个的 |