对多个表进行SELECT查询

时间:2010-07-28 09:54:32

标签: sql mysql

我有两个表,foobar

+----+-----+    +----+-----+
| id | val |    | id | val |
+----+-----+    +----+-----+
|  1 | qwe |    |  1 | asd |
|  2 | rty |    |  3 | fgh |
+----+-----+    +----+-----+

id在这里不是唯一的。并非foo中的所有ID都具有bar中的等效ID,反之亦然。我需要计算两个表中具有特定ID的所有行,并将它们显示在新表中,例如:

+----+-----------+-----------+
| id | count_foo | count_bar |
+----+-----------+-----------+
|  1 |         1 |         1 |
|  2 |         1 |         0 |
|  3 |         0 |         1 |
+----+-----------+-----------+

我试过UNION SELECT

SELECT id, COUNT(id) AS count_foo, 0 AS count_bar FROM foo GROUP BY id
UNION SELECT id, 0, COUNT(id) FROM bar GROUP BY id;

但这会输出id=1行两次,如

+----+-----------+-----------+
| id | count_foo | count_bar |
+----+-----------+-----------+
|  1 |         1 |         0 |  <- not good
|  2 |         1 |         0 |
|  1 |         0 |         1 |  <- not good
|  3 |         0 |         1 |
+----+-----------+-----------+

我也试过LEFT JOIN

SELECT id, COUNT(foo.id) AS count_foo, COUNT(bar.id) AS count_bar
FROM foo LEFT JOIN bar USING(id) GROUP BY id;

但是此查询会忽略表bar中的行foo中缺少ID的行:

+----+-----------+-----------+
| id | count_foo | count_bar |
+----+-----------+-----------+
|  1 |         1 |         1 |
|  2 |         1 |         0 |
+----+-----------+-----------+  <- can I haz `id=3`?

我错过了什么?什么是正确的查询或正确的手册?

感谢。

2 个答案:

答案 0 :(得分:5)

您可能需要尝试以下操作:

SELECT d.id,
       (SELECT COUNT(*) FROM foo WHERE id = d.id) count_foo,
       (SELECT COUNT(*) FROM bar WHERE id = d.id) count_bar
FROM   ((SELECT id FROM foo) UNION (SELECT id FROM bar)) d;

测试用例:

CREATE TABLE foo (id int, val varchar(5));
CREATE TABLE bar (id int, val varchar(5));

INSERT INTO foo VALUES (1, 'qwe');
INSERT INTO foo VALUES (2, 'rty');
INSERT INTO bar VALUES (1, 'asf');
INSERT INTO bar VALUES (3, 'ghj');

结果:

+------+-----------+-----------+
| id   | count_foo | count_bar |
+------+-----------+-----------+
|    1 |         1 |         1 |
|    2 |         1 |         0 |
|    3 |         0 |         1 |
+------+-----------+-----------+
3 rows in set (0.00 sec)

答案 1 :(得分:0)

你正在寻找OUTER JOIN吗?