我有a
次竞价和b
次竞价:
表a
(拍卖):
id status
1 1
2 0
3 0
4 1
表b
(投标):
id auction_id amount date
1 1 0.1 2018-01-24
2 1 0.1 2018-01-24
3 4 0.2 2018-01-26
4 4 0.1 2018-01-26
5 4 0.3 2018-01-28
6 1 0.1 2018-01-29
我想得到的是出价金额,出价总额,每个竞价的最后出价日期b
以及表格a
中所有内容的ID和状态状态:
这样的事情:
id status bid_sum bid_count last_bid_date
4 1 0.6 3 2018-01-28
1 1 0.3 3 2018-01-29
3 0 0 0 0000-00-00
2 0 0 0 0000-00-00
到目前为止,我有这个问题:
SELECT a.id, a.status, SUM( b.amount ) as bids_sum, COUNT( b.id ) as bids_count, MAX( b.dt ) as last_bid_date
FROM a, b
GROUP BY a.id
ORDER BY a.status DESC, a.id DESC
问题是它只返回至少有1个出价的拍卖
id status bid_sum bid_count last_bid_date
4 1 0.6 3 2018-01-28
1 1 0.3 3 2018-01-29
我需要所有拍卖。你能帮忙吗?谢谢!
答案 0 :(得分:2)
SELECT
a.id,
a.status,
COALESCE(SUM(b.amount), 0) as bids_sum,
COUNT(b.id) as bids_count,
COALESCE(MAX(b.dt), '0000-00-00') as last_bid_date
FROM a left outer join b
on a.id = b.auction_id
GROUP BY a.id
ORDER BY a.status DESC, a.id DESC
答案 1 :(得分:1)
您要做的是left join
:
SELECT a.id,
a.status,
SUM(b.amount) AS bids_sum,
COUNT(b.id) AS bids_count,
MAX(b.dt) AS last_bid_date
FROM a
LEFT JOIN b ON a.id = b.auction_id
GROUP BY a.id
ORDER BY a.status DESC,
a.id DESC