首页 > 解决方案 > 只从右连接mysql获取一个数据

问题描述

我的数据库中有表 2 表

1. 聊天

ID 电话号码 消息 created_at
1 898000211900 你好,法力乌唐木? 2021-10-25 11:36:26
1 898000211900 2021-10-25 09:36:26
1 798000211901 2021-10-25 09:36:26

2. 联系方式

ID 电话号码 姓名
1 898000211900 伊拉姆

我想对该表进行查询,该表仅显示一条消息(最新),如下所示:

电话号码 姓名 消息
898000211900 伊拉姆 你好,法力乌唐木?
798000211901 无效的

我尝试过 RIGHT JOIN 但结果是错误的

select 
contacts.name, 
contacts.phone_number,
chats.messages
from contacts
right join chats
on contacts.phone_number = chats.phone_number
order by chats.created_at desc

标签: mysqldatabase

解决方案


检查第二个表中的 NULL 值

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

SELECT contacts.name, contacts.phone_number, chats.messages
FROM contacts RIGHT JOIN chats
ON contacts.phone_number = chats.phone_number
GROUP BY contacts.phone_number
HAVING chats.name IS NOT NULL
ORDER BY chats.created_at DESC

推荐阅读