我一直在寻找很多有同样问题的人,但解决方案似乎更加不同?!
我有 3 张桌子:
+-------------------------------------------+
| ITEM: itemid(pk), status(fk), owner(fk) |
| |
| STATUS: statusid(pk), statusname |
| |
| OWNER: ownerid(pk), ownername |
+-------------------------------------------+
我有 2 个状态:1: Available,2: Broken。
在这种情况下,只有一个所有者拥有一件破损的物品。我正在使用此代码。首先它是不同的,但似乎 LEFT JOIN 和 GROUP/ORDER BY 应该可以解决问题。对我来说很不幸。
SELECT ownername, SUM(price) AS 'totalbrokenpriceeach', COUNT( itemid ) AS 'totalbrokenitemseach'
FROM item
LEFT JOIN owner ON item.owner = owner.ownerid
LEFT JOIN status on item.status = status.statusid
WHERE statusid='2'
GROUP BY ownerid
这将返回:
ownername totalbrokenpriceeach totalbrokenitemseach
Owner #1 60 1
Owner #5 180 4
我想返回:
ownername totalbrokenpriceeach totalbrokenitemseach
Owner #1 60 1
Owner #2 0 0
Owner #3 0 0
Owner #4 0 0
Owner #5 180 4
该怎么办?任何人有任何解决方案?
编辑:
OWNER
+-----------------------+
| ownerid ownername |
| 1: Henk |
| 2: Jan |
| 3: Piet |
| 4: Klaas |
+-----------------------+
STATUS
+-----------------------+
| statusid statusbeschr |
| 1: Available |
| 2: Broken |
+-----------------------+
ITEM
+--------------------------------------+
| itemid price owner status |
| 1: 90 1 1 |
| 2: 40 2 1 |
| 3: 20 2 1 |
| 4: 120 3 2 |
+--------------------------------------+
I need returned:
+-------------------------------------------------------+
| ownername SumOfBrokenItems AmountOfBrokenItems |
| Henk: 0 0 |
| Jan: 0 0 |
| Piet: 120 1 |
| Klaas: 0 0 |
+-------------------------------------------------------+