Mysql 如何使用2个具有或不具有重复记录的联接表来选择sql数据
我有一个mysql select语句,如下所示:-Mysql 如何使用2个具有或不具有重复记录的联接表来选择sql数据,mysql,select,Mysql,Select,我有一个mysql select语句,如下所示:- select user.username, chat.from_user,chat.to_user,chat.message,chat.date_created from chat join user on (chat.from_user or chat.to_user) in (user.user_id) where(chat.from_user = 3 or chat.to_user = 3) and chat.chat_id I
select user.username, chat.from_user,chat.to_user,chat.message,chat.date_created
from chat join user on (chat.from_user or chat.to_user) in (user.user_id)
where(chat.from_user = 3 or chat.to_user = 3) and chat.chat_id IN
(SELECT distinct (MAX(chat.chat_id) )
FROM chat GROUP BY chat_group_id);
这是我的结果
我总是得到username=admin。我的预期结果是用户名将从/到用户获得正确
请帮忙。谢谢。我想你打算:
select u.username, c.from_user, c.to_user, chat.message, c.date_created
from chat c join
user u
on u.user_id in (c.from_user, c.to_user)
where 3 in (c.from_user, c.to_user) and
c.chat_id in (select max(c2.chat_id)
from chat c2
group by chat_group_id
);
这不是你的结果已经正确了吗?嗨,Akhang,不,结果将返回username=admin(userid=1)。我想要的是,如果用户id=2,那么username将从用户id=3返回username(根据所附的屏幕截图-记录1),Hi Gordon,thx,谢谢您的帮助。但是,我从您的select语句中获得了重复记录(重复消息列)。Hi kasnady,thx感谢您的帮助。你的陈述接近我想要的。对于用户名,如何显示“对方”用户名。示例:如果我的语句是(chat.from_user=3或chat.to_user=3),则我的用户名将显示除3以外的用户名?
SELECT
IF(chat.from_user=3, to_user
, IF(chat.to_user=3, form_user, 0)) AS username,
chat.from_user,chat.to_user,chat.message,chat.date_created
FROM chat
LEFT JOIN user fr_user ON chat.from_user = user.user_id
LEFT JOIN user to_user ON chat.to_user = user.user_id -- since you only want to show the TO_USERNAME, you can remove above line
WHERE (chat.from_user = 3 OR chat.to_user = 3) and chat.chat_id
IN
(SELECT distinct (MAX(chat.chat_id) )
FROM chat GROUP BY chat_group_id);