我得到了这个MySQL查询,输出ID为18的用户与其他用户的最新聊天消息。该查询有效,直到我加载最后JOIN
,用于计算未审核的msgs(unviewed_total
)的数量。我收到的错误是T2.rid1
和T2.rid2
的“找不到列”。无法弄清楚如何以适当的方式引用这些列。
SELECT T2.maxDate, T2.ava, T2.uname,chat.user_to,chat.user_from,chat.body,chat.request_id,chat.secondary_rid, T3.unviewed_total FROM
(SELECT T1.user2_id, users.uname, users.ava, max(cdate) maxDate, T1.rid rid1, T1.sec_rid rid2 FROM
(SELECT chat.user_to user2_id, max(msg_time) cdate,request_id rid,secondary_rid sec_rid
FROM chat WHERE chat.user_from=18
GROUP BY chat.user_to
union distinct
(SELECT chat.user_from user2_id, max(msg_time) cdate,request_id rid,secondary_rid sec_rid
FROM chat WHERE chat.user_to=18
GROUP BY chat.user_from)) T1
inner join users on (users.uid = T1.user2_id)
group by T1.user2_id
order by maxDate desc) T2
join chat on (T2.maxDate = chat.msg_time)
join (SELECT COUNT(viewed) unviewed_total FROM chat WHERE viewed='0' AND user_to=18 AND request_id IN (T2.rid1,T2.rid2)) T3
ORDER BY T2.maxDate DESC
答案 0 :(得分:1)
该联接的内部查询不知道表T2。 我建议将连接移动到select语句。
更改
SELECT T2.maxDate, T2.ava, T2.uname,chat.user_to,chat.user_from,chat.body,chat.request_id,chat.secondary_rid, T3.unviewed_total FROM
到
SELECT T2.maxDate, T2.ava, T2.uname,chat.user_to,chat.user_from,chat.body,chat.request_id,chat.secondary_rid, (SELECT COUNT(viewed) unviewed_total FROM chat WHERE viewed='0' AND user_to=18 AND request_id IN (T2.rid1,T2.rid2)) unviewed_total
此处有关此技术的更多信息:https://www.essentialsql.com/get-ready-to-learn-sql-server-20-using-subqueries-in-the-select-statement/