gpt4 book ai didi

mysql - SQL 查询以检索来自所有用户 friend 的消息

转载 作者:搜寻专家 更新时间:2023-10-30 23:15:21 25 4
gpt4 key购买 nike

我为一个 Twitter 克隆网站设置了 3 个数据库。

表“用户”:

email | firstname | lastname | hash_password

链接表“ friend ”:

email | friend

这列出了所有用户和他们的 friend 。友谊是单向的(如 Twitter 的“关注”/“关注者”)。friends 表是一个链接表,用于列出所有用户的 friend 。所以 friends.userfriends.friend 都是 users.email 的外键。

表“消息”:

timestamp | user | content

什么是用于检索来自用户及其好友的所有消息的 SQL 查询?


我试过:

SELECT
'timestamp',
user,
content
FROM
messages
INNER JOIN friends ON messages.user = friends.friend
ORDER BY 'timestamp' DESC;

这似乎正确地加入了他们,但我如何才能只获取特定用户(电子邮件地址) friend 的消息。现在这只会返回所有消息。

谢谢。

最佳答案

timestamp 的引号应该带有反引号,否则 MySQL 将假定为字符串文字值。

否则,要返回来自用户和所有 friend 的消息,您可以使用UNION。一半返回用户的消息,另一半返回 friend 的消息。您需要将用户的电子邮件添加到您的加入条件:

/* First part of the UNION returns friends messages */
SELECT
`timestamp`,
user,
content
FROM
messages
/* The join ON clause specifies the main user email */
INNER JOIN friends
ON messages.user = friends.friend
AND friends.email = 'email@example.com'
UNION ALL
/* Other part of the UNION just gets all messages for the main user by email addr */
SELECT
`timestamp`,
user,
content
FROM
messages
WHERE user = 'email@example.com'
/* ORDER BY applies to everything */
ORDER BY `timestamp` DESC;

如果您想在此处加入用户信息(名字/姓氏),最简单的方法是将整个内容包装在一个子查询和连接。

SELECT
users.*,
messages_sub.content,
messages_sub.`timestamp`
FROM
users
JOIN (/* The entire thing from above */) AS messages_sub ON users.email = messages_sub.user
ORDER BY `timestamp`

它也可以通过您要查找的文字电子邮件地址和好友列表的 UNION 来完成,只生成一个外部查询。这有点棘手,但最终可能会更快。在此处引入 users 表中的其他列也不会造成混淆。我将添加名称:

SELECT
`timestamp`,
user,
firstname,
lastname,
content
FROM
messages
INNER JOIN (
/* Union query produces a list of email addrs -
the person you're looking for plus all his friends
Starts with string literal for the main user
*/
SELECT 'email@example.com' AS email
UNION
/* Plus all his friends into one list joined against messages */
SELECT friend AS email FROM friends WHERE email = 'email@example.com'
) user_and_friends ON messages.user = user_and_friends.email
/* Join against the users table for name info */
INNER JOIN users ON user_and_friends.email = users.email
ORDER BY `timestamp` DESC

关于mysql - SQL 查询以检索来自所有用户 friend 的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com