我有以下mysql查询来获取每个账单的总金额和税额。
SELECT b.bill_no
, b.total_amount
, b.created_at
, b.id
, ( SELECT sum(gst_amt)
FROM bill_contents_pharmacy bc
WHERE bc.bill_id = b.id) as tgst
FROM bills b
WHERE b.bill_type = 'pharmacy'
AND cast(b.cr_at as date) >= '2017-08-01'
AND cast(b.cr_at as date) <= '2017-08-23'
AND b.is_cancelled = 0
AND b.is_deleted = 0
ORDER
BY b.bill_no ASC
这个查询在我的PHP代码中大约需要10分钟,但是当我在phpmyadmin中运行它时,它只用了3.6秒。我做错了什么?
答案 0 :(得分:0)
问题似乎是子查询。请尝试使用连接。
SELECT b.bill_no, b.total_amount,b.created_at, b.id, sum(bc.gst_amt) as tgst
FROM bills b LEFT JOIN bill_contents_pharmacy bc ON (bc.bill_id = b.id)
WHERE b.bill_type = 'pharmacy' AND cast(b.cr_at as date) >= '2017-08-01'
AND cast(b.cr_at as date) <= '2017-08-23'
AND b.is_cancelled IS FALSE AND b.is_deleted IS FALSE
GROUP BY b.bill_no, b.total_amount, b.created_at, b.id
ORDER BY b.bill_no ASC
此外,可能没有必要进行铸造。
答案 1 :(得分:0)
你也可以尝试这个,你必须在账单和bill_contents_pharmacy表上创建关系并创建索引。
SELECT b.bill_no, b.total_amount, b.created_at, b.id, sum(bc.gst_amt) as tgst
FROM bills b
JOIN bill_contents_pharmacy bc ON bc.bill_id = b.id
WHERE b.bill_type = 'pharmacy'
AND cast(b.cr_at as date) >= '2017-08-01'
AND cast(b.cr_at as date) <= '2017-08-23'
AND b.is_cancelled = 0
AND b.is_deleted = 0
GROUP BY b.bill_no, b.total_amount, b.created_at, b.id
ORDER BY b.bill_no ASC
这必须加快查询速度