SQL 从其他表中给定时间戳后的记录中选择
Posted
技术标签:
【中文标题】SQL 从其他表中给定时间戳后的记录中选择【英文标题】:SQL Select from records after given timestamp within other table 【发布时间】:2019-06-24 21:56:16 【问题描述】:我做了 2 张桌子。 一个用于消息,另一个用于已删除聊天。 如果有人删除了聊天,那么它应该只显示删除时间戳后的新消息
请在您的回答中使用这些表/列名称:
user_messages: user_id, chat_id, timestamp
user_chats_deleted: user_id, chat_id, timestamp
我的 SQL 代码:
SELECT * FROM user_messages um
LEFT JOIN (
SELECT *
FROM user_chats_deleted
GROUP BY timestamp Order by timestamp ASC Limit 1
)ud ON (um.chat_id = ud.chat_id and um.user_id = ud.user_id and ud.timestamp < um.timestamp)
where um.chat_id = '4' ORDER BY um.timestamp ASC
它显示消息,但不是我想要的:/
【问题讨论】:
select * from user_messages where timestamp > (select timestamp from user_chats_deleted where chat_id = 4 order by timestamp desc limit 1) and chat_id = 4
也许这会有所帮助
您应该将 user_chats_deleted 中的 user_messages id 映射为 user_messages_id。这会更容易。
@abhishek 这是真正的方法,但它不起作用。已将其更改为:
timestamp > EXISTS(从 user_chats_deleted 中选择时间戳,其中 chat_id = '".$getChatid."' and user_id = '".$user->id."' order by timestamp DESC limit 1)跨度>
不选择删除用户聊天的时间戳
【参考方案1】:
您可以尝试几个不同的查询,尽管它们都应该做同样的事情:
SELECT *
FROM user_messages um
WHERE um.timestamp >
( SELECT MAX(um.timestamp)
FROM user_chats_deleted ucd
WHERE ucd.user_id = um.user_id
AND ucd.chat_id = um.chat_id
);
更简洁、更易读/易懂的 SQL 脚本:
WITH Last_Deleted_Message AS
(
SELECT user_id
, chat_id
, MAX(timestamp) AS max_deleted_timestamp
FROM user_chats_deleted ucd
GROUP
BY user_id
, chat_id
)
SELECT user_id
FROM user_messages um
JOIN Last_Deleted_Message ldm
ON um.user_id = ldm.user_id
AND um.chat_id = ldm.chat_id
AND um.timestamp > ldm.max_deleted_timestamp
WHERE um.chat_id = '4'
ORDER
BY um.timestamp ASC;
【讨论】:
以上是关于SQL 从其他表中给定时间戳后的记录中选择的主要内容,如果未能解决你的问题,请参考以下文章