我有三个表,比如t1,t2,t3,列为
t1.c1, t1.c2, t1.c3
t2.c4, t2.c1, t2.c5
t3.c6, t3.c4
t1.c1,t2.c4和t3.c6是各自表格的主要自动增量字段。
t2.c1是t2中的外键,指的是t1中的t1.c1
t3.c4是t3中的外键,指的是t2中的t2.c4
我希望得到t2.c5(比如X)
的任何给定值的以下输出SORRY - 输出栏中的错误!
我希望输出
t2.c4, t1.c2, count
而非
t2.c1, t1.c2, count
其中count是给定t2.c5值的t3中的记录数,如果没有记录,则必须为零,其中t2.c5 = X且t3.c4 = t2.c4
这可以在一个选择查询中完成吗?
以下是示例数据:
表:t1
+------+-------+------+
| c1 | c2 | c3 |
+------+-------+------+
| 1 | 11111 | 111 |
| 2 | 22222 | 222 |
| 3 | 33333 | 333 |
+------+-------+------+
表:t2
+------+------+------+
| c4 | c1 | c5 |
+------+------+------+
| 1 | 1 | 11 |
| 2 | 1 | 11 |
| 3 | 2 | 11 |
| 4 | 2 | 12 |
| 5 | 3 | 12 |
| 6 | 2 | 12 |
+------+------+------+
表:t3
+------+------+
| c6 | c4 |
+------+------+
| 1 | 1 |
| 2 | 1 |
| 3 | 5 |
+------+------+
对于t2.c5=11
,输出为
+-------------------+
t2.c4 | t1.c2| Count
+-------------------+
1 | 11111| 2
2 | 11111| 0
3 | 22222| 0
+-------------------+
对于t2.c5=12
,输出为
+-------------------+
t2.c4 | t1.c2| Count
+-------------------+
4 | 22222| 0
5 | 33333| 1
6 | 22222| 0
答案 0 :(得分:1)
SELECT t2.c1, t1.c2, count(*)
FROM t1 inner join t2 using (c1)
inner join t3 using (c4)
GROUP BY t2.c5, t2.c1, t1.c2
这里令人困惑的是你要选择t2.c1,t1.c2 对于任何t2.c5的值。
你必须决定如上所示对所有三列进行分组,或者真正按t2.c5进行分组,并且只显示t2.c2,t1.c2的任何值,这将需要对它们使用一些聚合函数。例如:
SELECT max(t2.c1) c2, max(t1.c2) c2, count(*)
FROM t1 inner join t2 using (c1)
inner join t3 using (c4)
GROUP BY t2.c5
答案 1 :(得分:1)
尝试此查询:
SELECT t2.c4, t1.c2, COUNT(t3.c6)
FROM t1
INNER JOIN t2 ON t1.c1 = t2.c1
LEFT JOIN t3 ON t3.c4 = t2.c4
WHERE t2.c5 = '11'
GROUP BY t2.c4, t1.c2
<强>输出:强>
c4 c2 count
-------------
1 11111 2
2 11111 0
3 22222 0
使用此查询:
SELECT t2.c4, t1.c2, COUNT(t3.c6) as count
FROM t1
INNER JOIN t2 ON t1.c1 = t2.c1
LEFT JOIN t3 ON t3.c4 = t2.c4
WHERE t2.c5 = '12'
GROUP BY t2.c4, t1.c2
输出是:
c4 c2 count
-----------------
4 22222 0
5 33333 1
6 22222 0