我试图显示一个“空”'使用' IFNULL'将值设为0但它返回所有行为null或0.一切正常,直到我添加' lounge2'桌子和' lounge2order2'表。 order2.lounge2orderid是' NULL'。我知道这与“加入”有关。但不确定在哪里或哪个地方实施。
谢谢大家......
SELECT orders2.orderid, orders2.orderdate, branch2.branchname, COUNT(orders2.garment2orderid) AS 'no gar orders', SUM(garment2.hireprice) as 'total gar sold',
COUNT(orders2.lounge2orderid+IFNULL(orders2.lounge2orderid,0)) as 'No of lounge sales', SUM(lounge2.hirerate)
from orders2, branch2, garment2, garment2order2, lounge2, lounge2order2
WHERE orders2.orderid IN
(SELECT orders2.orderid FROM orders2
WHERE orders2.branchid = 2
AND YEAR(orders2.orderdate)= 2011)
AND branch2.branchid IN
(SELECT branch2.branchid from branch2
WHERE branch2.branchid = orders2.branchid)
AND garment2order2.garment2orderid IN
(SELECT garment2order2.garment2orderid FROM garment2order2
WHERE garment2order2.garment2orderid = orders2.garment2orderid)
AND garment2.garmentid IN
(SELECT garment2.garmentid FROM garment2
WHERE garment2.garmentid = garment2order2.garmentid)
AND lounge2order2.lounge2orderid IN
(SELECT lounge2order2.lounge2orderid FROM lounge2order2
WHERE lounge2order2.lounge2orderid = orders2.lounge2orderid)
AND lounge2.loungeid IN
(SELECT lounge2.loungeid FROM lounge2
WHERE lounge2.loungeid = lounge2order2.loungeid)
答案 0 :(得分:1)
首先,尽量避免FROM orders2, branch2, garment2, garment2order2, lounge2, lounge2order2
它必须是JOIN ... ON
语句。这将有助于您调试,让我们了解您的逻辑和表关系。
要使SUM
或COUNT
等任何agregate函数正常工作,您应该设置GROUP BY
语句。
因为我不知道您的数据库结构是什么样的。
这是我的尝试:
SELECT
orders2.orderid,
orders2.orderdate,
COUNT(orders2.garment2orderid) AS 'no gar orders',
branch2.branchname,
SUM(garment2.hireprice) as 'total gar sold',
SUM(IF(orders2.lounge2orderid IS NULL,1,0)) as 'No of lounge sales',
SUM(lounge2.hirerate)
FROM orders2
LEFT JOIN branch2
ON branch2.branchid = orders2.branchid
LEFT JOIN garment2order2
ON garment2order2.garment2orderid = orders2.garment2orderid
LEFT JOIN garment2
ON garment2.garmentid = garment2order2.garmentid
LEFT JOIN lounge2order2
ON lounge2order2.lounge2orderid = orders2.lounge2orderid
LEFT JOIN lounge2
ON lounge2.loungeid = lounge2order2.loungeid)
WHERE orders2.branchid = 2
AND YEAR(orders2.orderdate)= 2011
GROUP BY orders2.orderid