如何在DirectMessage查询中添加对发件人姓名的LIKE搜索?
修改SQL以支持发件人姓名模糊搜索的方案
以下是调整后的SQL语句,新增了关联User表并支持对发件人姓名(FIRST_NAME/LAST_NAME)进行模糊搜索的逻辑:
SELECT outerDM.* FROM direct_message outerDM INNER JOIN (SELECT dm.ultimate_parent_id, MAX(dm.sent_at) AS last_sent FROM direct_message dm INNER JOIN user u ON dm.sender_id = u.id WHERE dm.recipient_id = :recipientId AND ( UPPER(dm.title) LIKE UPPER(CONCAT('%', :searchQuery, '%')) OR UPPER(u.first_name) LIKE UPPER(CONCAT('%', :searchQuery, '%')) OR UPPER(u.last_name) LIKE UPPER(CONCAT('%', :searchQuery, '%')) ) GROUP BY dm.ultimate_parent_id) innerDM ON outerDM.ultimate_parent_id = innerDM.ultimate_parent_id AND outerDM.sent_at = innerDM.last_sent -- 若需要返回发件人信息,可取消下方注释 -- INNER JOIN user sender ON outerDM.sender_id = sender.id ORDER BY outerDM.sent_at DESC
关键调整说明:
- 在子查询中新增
INNER JOIN user u ON dm.sender_id = u.id,关联发件人对应的用户数据 - WHERE条件中扩展了两个OR分支,将发件人的名和姓纳入模糊搜索范围,且保持和原标题搜索一致的不区分大小写逻辑
- 若需要在最终结果中展示发件人姓名等信息,可以在主查询后再次关联User表(已在代码中给出注释示例)
内容的提问来源于stack exchange,提问作者lenny
相关产品推荐
相关产品推荐

