复杂的查询逻辑

时间:2013-05-01 03:30:57

标签: mysql sql database

我想运行一个有点复杂的mySQL查询,而我在思考如何编写它时遇到了困难。

基本上我有三张桌子:

a(aid, name);
b(bid, val);
ab(aid, bid)

我想要做的是创建一个创建如下表格的查询:

c(aid, valSum);

我希望valSum从0开始,并添加援助和出价之间每个关系的bid.val值。

例如:

a:
+-----+------+
| aid | name |
+-----+------+
| 1   |  Joe |
| 2   |  Jon |
| 3   |  Max |
+-----+------+

b:
+-----+-----+
| bid | val |
+-----+-----+
| 1   |   2 |
| 2   |   4 |
| 3   |   6 |
+-----+-----+

ab:
+-----+-----+
| aid | bid |
+-----+-----+
| 1   |   1 |
| 1   |   2 |
| 2   |   2 |
| 2   |   3 |
| 3   |   1 |
| 3   |   2 |
| 3   |   3 |
+-----+-----+

c:
+-----+--------+
| aid | valSum |
+-----+--------+
| 1   |      6 |
| 2   |     10 |
| 3   |     12 |
+-----+--------+

2 个答案:

答案 0 :(得分:4)

如下所示:

SELECT a.aid, SUM(b.val) AS valSum
FROM a
INNER JOIN ab ON a.aid = ab.aid
INNER JOIN b ON ab.bid = b.bid
GROUP BY a.aid

答案 1 :(得分:1)

您根本不需要加入表格a

SELECT ab.aid, sum(b.val) AS valSum
FROM   ab
JOIN   b USING (bid)
GROUP  BY 1;

...除了列出a中没有任何匹配的ab行。在这种情况下,您必须使用 LEFT JOIN

SELECT a.aid, sum(b.val) AS valSum
FROM   a
LEFT   JOIN ab USING (aid)
LEFT   JOIN  b USING (bid);
GROUP  BY 1;
对于那些行,

valSumNULL