我有3张关于投诉的表格。第一个表由抱怨信息本身组成,第二个表是带有status_id的complain_review,第三个表是包含状态信息的status_id表。我正在尝试从抱怨中选择抱怨抱怨,从抱怨请求中选择最新的status_id(按日期排序),并将其与抱怨信息联系起来。
这是我尝试过的(到目前为止没有成功):
SELECT c1.complain_desc, c2.status_id, c2.name as statusDesc from complain c1
left join
(SELECT c3.status_id, c4.name, c3.complain_id FROM complain_review c3
inner join complain_status c4 on c4.id=c3.status_id ORDER by c3.date DESC) c2
on c2.complain_id=c1.id
这是@maheshiv提供的更新示例
..我搜索过该网站,但我不确切知道要搜索的关键字:(
编辑:我在http://sqlfiddle.com/#!9/d86a7a/2建立了一个架构,所以也许有人可以更好地看一下这些表
编辑:也许这将是我能得到的最接近......并且正在工作!
SELECT c.complain_desc, cr1.status_id, cs.name
FROM complain c
INNER JOIN complain_review cr1 ON c.id=cr1.complain_id
INNER JOIN complain_status cs ON cs.id=cr1.status_id
WHERE cr1.date = (SELECT MAX(cr2.date) FROM complain_review cr2
WHERE cr1.complain_id = cr2.complain_id)
答案 0 :(得分:1)
我试图从抱怨中选择抱怨,并从抱怨请求中选择最新的status_id(按日期排序),并将其与抱怨信息联系起来。
这是关于Stack Overflow的一个非常常见的问题。您可以按照greatest-n-per-group找到许多解决方案。
以下是使用您的示例的解决方案:
round
这是一个不使用子查询的不同解决方案:
SELECT c.complain_desc, latest_cr.status_id, cs.name AS status_desc
FROM complain AS c
INNER JOIN (
SELECT complain_id, status_id
FROM (
SELECT cr.complain_id, cr.status_id,
IF(@cgroup=cr.complain_id, @rownum:=@rownum+1, 1) AS rownum,
(@cgroup:=cr.complain_id)
FROM (SELECT @cgroup:=0, @rownum:=1) AS _init
CROSS JOIN complain_review AS cr
ORDER BY cr.complain_id DESC, cr.date DESC
) AS n
WHERE n.rownum = 1
) AS latest_cr
ON c.id=latest_cr.complain_id
INNER JOIN complain_status AS cs
ON cs.id = latest_cr.status_id;
答案 1 :(得分:-1)
我想你可能需要这个查询, 我相信max status_id是投诉的最新状态。根据{{3}}
select c1.complain_desc, c2.status_id, c3.name from complain c1 inner join (select complain_id, max(status_id) from complain_review group by complain_id) c2 on c1.id=c2.complain_id inner join complain_status c3 on c3.id=c2.status_id;