mysql - 只从右连接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
解决方案
检查第二个表中的 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
推荐阅读
- r - R:如果列中的值位于其他两列中的可能值对之间,则确定每组的行号
- excel - 验证对于一列中的每个单元格值,该行中仅存在一个唯一的单元格组合
- .net - AngularJS:动态加载的组件未显示
- ios - iOS 代码签名 Fastlane 匹配错误
- cordova - cordovaFileTransfer 下载 - 未找到证书路径的信任锚
- android - Kotlin:将 'cascade if' 替换为 'when' 与其他变量进行比较
- java - Xpath - 需要 Gmail 电子邮件正文的定位器才能阅读发送的邮件
- cuda - 单个线程的全局内存访问
- reactjs - 向作为道具传递的组件添加额外的道具
- node.js - 创建大对象时,Node.js 进程挂起