这是我的SQL表结构:SQL查询合并两个查询到一个空行
表1:细节
|--id--|--id_user--|--price--|
| 1 | 1 | 10 |
| 2 | 2 | 15 |
| 3 | 1 | 25 |
| 4 | 3 | 30 |
| 5 | 3 | 7 |
------------------------------
表2:用户
|--id--|--id_country--|
| 1 | 1 |
| 2 | 2 |
| 3 | 0 |
-----------------------
表3:国家
|--id--|--country--|
| 1 | France |
| 2 | Italy |
--------------------
我需要的是t Ø按国家得到价格的总和:
SELECT c.country, SUM(d.price) AS price
FROM details d
INNER JOIN users u ON u.id = d.id_user
INNER JOIN country c ON c.id = u.id_country
GROUP BY c.country
ORDER BY c.country
我得到这个:
|--country--|--price--|
| France | 35 |
| Italy | 15 |
-----------------------
但我需要得到这个:
|--country--|--price--|
| France | 35 |
| Italy | 15 |
| Undefined | 37 |
-----------------------
其中undefined
是,如果id_country=0
。 (我不能添加到国家表id=0 or id=undefined
,它会弄乱其他东西)。现在,我通过两个单独的查询实现这一目标,第二个是:
SELECT SUM(d.price) as price
FROM details d
INNER JOIN users u ON u.id = d.id_user AND u.id_country=0
GROUP BY u.id_country
我在想,如果...... 是有可能做到这一点在一个查询?
切换到左加入国家。 – jarlh
RIGHT JOIN'INNER JOIN country c' –
很奇怪的是,您可以在不存在的用户表中使用id_country。这表明你不正确地使用你的数据库。如果你想允许“未定义的国家”,你应该有一个外键约束,并使列可以为空。 –