mysql - 如何使用2个带有OR条件的连接表来选择没有重复记录的sql数据

标签 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 IN
(SELECT distinct (MAX(chat.chat_id) )
    FROM chat GROUP BY chat_group_id);

这是我的结果

enter image description here

我总是得到用户名= admin。我的预期结果是用户名将得到正确的用户名。

请帮忙。谢谢。

最佳答案

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);

关于mysql - 如何使用2个带有OR条件的连接表来选择没有重复记录的sql数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48919125/

相关文章:

Select 语句中的 PHP 变量

java - 如何根据外键从引用表中获取值?

mysql - 使用 Jhipster 中的服务用用户上传的 CSV BLOB 实体填充第二个实体

mysql - Django 模型创建时的竞争条件

php - 使用 PHP 在 MySQL 数据库中自动加密?

sql - 选择问题

php - MySQL - 跨两个表的最佳实践

java - 如何使用Java从特定服务器访问数据库?

sql - 选择不同和非不同的列值

SQL - 如何检索一列中排名最高的行,而另一列中具有多个重复行