编写MySQL查询的更好方法是什么?

时间:2013-01-31 16:09:22

标签: mysql

我有一个MySQL查询

SELECT *,
       (SELECT COUNT(*) FROM B WHERE B.AID = A.ID) AS Sum1,
       (SELECT COUNT(*) FROM C WHERE C.AID = A.ID) AS Sum2
FROM A

使用连接的可能替代方法是什么?

3 个答案:

答案 0 :(得分:2)

SELECT A.*, IFNULL(t1.sum, 0), IFNULL(t2.sum, 0)
FROM A
LEFT JOIN (SELECT AID, COUNT(AID) sum FROM B GROUP BY AID) t1 ON t1.AID = A.ID
LEFT JOIN (SELECT AID, COUNT(AID) sum FROM C GROUP BY AID) t2 ON t2.AID = A.ID

答案 1 :(得分:2)

如果B和C表中有唯一的ID,这将有效。在我的示例中,字段称为ID。

SELECT A.*,
       COUNT(DISTINCT B.ID) AS Sum1,
       COUNT(DISTINCT C.ID) AS Sum2

FROM   A

       LEFT JOIN B ON b.AID = A.ID
       LEFT JOIN C ON C.AID = A.ID

GROUP BY A.ID

答案 2 :(得分:0)

不确定这是否是您正在寻找的,以下是如何使用join实现:但假设......您的表格看起来像我用作演示的样本。如果不是,请与我们分享您的表格架构和样本数据,以及您的预期结果......

http://sqlfiddle.com/#!2/1e65c/2

SELECT A.ID, A.NAME, 
CASE WHEN B.AID = A.ID THEN COUNT(*) END AS SUM1,
CASE WHEN B.AID = A.ID THEN COUNT(*) END AS SUM1
FROM A
INNER JOIN B
ON A.ID = B.AID
INNER JOIN C
ON B.AID = C.AID
GROUP BY A.ID, A.NAME
;

SELECT A.ID, A.NAME,  COUNT(B.AID) AS SUM1,
COUNT(C.AID) AS SUM1
FROM A
INNER JOIN B
ON A.ID = B.AID
INNER JOIN C
ON B.AID = C.AID
GROUP BY A.ID, A.NAME
;

| ID | NAME | SUM1 |
--------------------
|  1 | John |    2 |
|  2 |  Tim |    4 |
|  3 | Jack |    2 |