我有两张桌子
工作:
jobID,col1,col2
并出价:
bidID,jobID,出价,状态
任何工作都可以针对它进行无限数量的出价。
我想在表格客户端显示结果,显示所有工作详情,以及每个工作的最高出价和该出价的状态。
我似乎能够显示最高出价,但不能显示该出价的相应状态。
感谢您的帮助!
SELECT jobs.jobID as jobID, jobs.col1 as col1, jobs.col2 as col2,
MAX(bids.bid) as bid, bids.status as status
FROM jobs
JOIN bids on jobs.jobID = bids.jobID
GROUP BY jobID
ORDER BY bid desc;
答案 0 :(得分:1)
您可以使用substring_index()
/ group_concat()
技巧:
SELECT j.*, MAX(b.bid) as bid,
substring_index(group_concat(jb.status order by b.bid desc), ',', 1) as status
FROM jobs j left join
jobbids jb
on j.jobID = jb.jobID left join
bids b
on jb.bidId = b.bidId
GROUP BY j.jobId
ORDER BY bid desc;
我做了以下更改:
jobs
中的所有行,因此我将join
更改为left join
。bids
表,因此我将其添加进来。注意:这假设出价数量不是太大。 MySQL具有(可配置的)group_concat()
生成的字符串的最大大小。
答案 1 :(得分:0)
尝试以下查询: -
SELECT jobs.jobID as jobID, jobs.col1 as col1, jobs.col2 as col2,
MAX(bids.bid) as bid, bids.status as status
FROM jobs
JOIN bids on jobs.jobID = bids.jobID
GROUP BY jobID, status
ORDER BY bid desc;
现在尝试编辑版本。 希望这会对你有所帮助。
答案 2 :(得分:0)
股票回答是一个无核的子查询,如手册(http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html)中所述
SELECT j.*
, x.*
FROM bids x
JOIN
( SELECT jobID,MAX(bid) max_bid FROM bid GROUP BY jobID ) y
ON y.jobID = x.jobID
AND y.max_bid = x.bid
JOIN jobs j
ON j.jobID = x.jobID;