任何人都可以帮我解决这个问题吗?
当我只加入2张桌子时。它工作正常。
但是当我试图从多个表中选择时。它不起作用。这是不工作代码的例子
SELECT ca.cdate as tarikh, sum(transaction.amount) as totalamount
FROM agent ag, town tw, calendar ca
LEFT JOIN transaction ON ca.cdate = DATE_FORMAT(transaction.created_at, '%Y-%m-%d')
WHERE ca.cdate >= '2014-06-01' AND ca.cdate <= '2014-06-11'
AND transaction.agent_id = ag.id
AND ag.town_id = tw.id
AND tw.state_id = 7;
结果是
按
添加组后SELECT ca.cdate as tarikh, sum(transaction.amount) as totalamount
FROM agent ag, town tw, calendar ca
LEFT JOIN transaction ON ca.cdate = DATE_FORMAT(transaction.created_at, '%Y-%m-%d')
WHERE ca.cdate >= '2014-06-01' AND ca.cdate <= '2014-06-11'
AND transaction.agent_id = ag.id
AND ag.town_id = tw.id
AND tw.state_id = 7
GROUP BY
ca.cdate;
尝试Ambrish的查询建议
SELECT ca.cdate as tarikh, sum(transaction.amount) as totalamount
FROM calendar ca
LEFT JOIN transaction ON ca.cdate = DATE_FORMAT(transaction.created_at, '%Y-%m-%d')
LEFT JOIN agent ag on transaction.agent_id = ag.id
LEFT JOIN town tw on ag.town_id = tw.id
WHERE ca.cdate >= '2014-06-01'
AND ca.cdate <= '2014-06-11'
AND tw.state_id = 7;
结果是
Ambrish的第二个SELECT ca.cdate as tarikh, sum(transaction.amount) as totalamount
FROM calendar ca
LEFT JOIN transaction ON ca.cdate = DATE_FORMAT(transaction.created_at, '%Y-%m-%d')
LEFT JOIN agent ag on transaction.agent_id = ag.id
LEFT JOIN town tw on ag.town_id = tw.id
WHERE ca.cdate >= '2014-06-01' AND ca.cdate <= '2014-06-11'
AND tw.state_id = 7
group by ca.cdate;
结果是
答案 0 :(得分:0)
SELECT ca.cdate as tarikh, sum(transaction.amount) as totalamount
FROM calendar ca
LEFT JOIN transaction ON ca.cdate = DATE_FORMAT(transaction.created_at, '%Y-%m-%d')
LEFT JOIN agent ag on transaction.agent_id = ag.id
LEFT JOIN town tw ag.town_id = tw.id
WHERE ca.cdate >= '2014-06-01' AND ca.cdate <= '2014-06-11'
AND tw.state_id = 7
group by ca.cdate;
如果没有返回结果,则可能没有匹配的记录。因此,请尝试不带(或子集)WHERE
子句的查询。或者具有不同值的查询。
答案 1 :(得分:0)
SELECT
calendar.cdate,
sum(transaction.amount)
FROM
calendar
LEFT JOIN
(
select transaction.amount, transaction.created_at from transaction, agent, town
where
transaction.agent_id = agent.id
and agent.town_id = town.id
and town.state_id = 14
)
transaction
ON calendar.cdate = DATE_FORMAT(transaction.created_at, "%Y-%m-%d")
WHERE
calendar.cdate >= '2014-06-01' and calendar.cdate <= '2014-06-11'
GROUP BY
calendar.cdate;
最后,我设法通过子查询找到答案。谢谢你的帮助..