**更新:标题应该是:Sql Query - 具有最新条目的唯一项目
你好,
我有两张桌子。用户和rsvp
用户具有用户详细信息(id,name,email)
rsvp中有rsvp状态(answerid,userid,eventid,answer)
注意:
回答1 =来
回答2 =没有来
回答3 =也许
回答4(伪回答)=没有回复
请注意,“回答4”从未出现在实际的rsvp表数据中。 它是使用下面的SQL
动态构建的查看即将到来的人,不是谁,可能会来的人以及没有回复的人的查询如下:
SELECT
usrs.name,
usrs.email,
(SELECT CASE
WHEN rsvp.answer = 1 THEN 'Yes, see you there'
WHEN rsvp.answer = 2 THEN 'Cannot make it'
WHEN rsvp.answer = 4 THEN 'Cannot make it'
WHEN rsvp.answer = 3 THEN 'Maybe'
ELSE 'No Reply' END) as attendance,
(SELECT CASE
WHEN rsvp.answer = 1 THEN "1"
WHEN rsvp.answer = 2 THEN "3"
WHEN rsvp.answer = 4 THEN "4"
WHEN rsvp.answer = 3 THEN "2"
ELSE "5" END) as ordering
FROM jos_users usrs
LEFT JOIN jos_rsvp as rsvp on usrs.id = rsvp.userid
WHERE usrs.id NOT IN (62,63,128)
ORDER BY ordering
同一位用户可能会多次回复。即首先他们回答是,然后他们改变主意并回复NO。
未更新rsvp答案,只需为新答案插入新记录。 上面的SQL的问题在于它不考虑这种重复。
我正在试图找出如何更改它,以便只在结果中显示每个用户的最后一个答案。起初看起来很简单,但现在我无法弄明白。
使用MySQL。
请帮助,
失去的头发
N4〜
答案 0 :(得分:1)
这个怎么样?
SELECT
usrs.name,
usrs.email,
(SELECT CASE
WHEN rsvp.answer = 1 THEN 'Yes, see you there'
WHEN rsvp.answer = 2 THEN 'Cannot make it'
WHEN rsvp.answer = 4 THEN 'Cannot make it'
WHEN rsvp.answer = 3 THEN 'Maybe'
ELSE 'No Reply' END) as attendance,
(SELECT CASE
WHEN rsvp.answer = 1 THEN "1"
WHEN rsvp.answer = 2 THEN "3"
WHEN rsvp.answer = 4 THEN "4"
WHEN rsvp.answer = 3 THEN "2"
ELSE "5" END) as ordering
FROM jos_users usrs, jos_rsvp rsvp,
(SELECT userid, max(answerid) AS latest_answerid
FROM jos_rsvp
WHERE userid NOT IN (62,63,128)
GROUP BY userid
) AS latest_rsvp
WHERE usrs.id = rsvp.userid
AND rsvp.userid = latest_rsvp.userid
AND rsvp.answerid = latest_rsvp.latest_answerid
ORDER BY ordering