gpt4 book ai didi

mysql - 表 JOIN 没有像在 mysql 中应该的那样工作

转载 作者:行者123 更新时间:2023-11-29 05:03:09 25 4
gpt4 key购买 nike

我有 2 个表,第一个是 users_table,第二个是 friends_table

users_table 包含有关用户的信息,包括 banned 列,而 friends_table 是用户之间的友谊。

两个表都有 user_id 列,所以我想要的是根据两个表的条​​件检索特定用户的好友数量。条件是 user_idbanned。我希望 friend 的数量不包括被禁止的用户,但即使用户 friend 被禁止,我仍然会得到 friend 总数。请帮助我,这是我同时运行以检索 friend 的查询:

$query1 = "
SELECT *
FROM users_table u
INNER JOIN friends_table f ON u.user_id = f.user_id
WHERE f.user_id = $user_id AND u.banned = 0
";

$query2 = "
SELECT *
FROM users_table u
INNER JOIN friends_table f ON u.user_id = f.friend_id
WHERE f.friend_id = $user_id AND u.banned = 0
";

编辑“用户表”结构:

user_id
first_name
last_name
username
email
password
temporarily_banned
banned

“friends_table”结构:

friendship_id
user_id
friend_id
friendship_timestamp

表记录示例

users_table 示例:

user_id: 20
first_name: Firas
last_name: Helou
username: firashelou
email: mac_987@hotmail.com
password: *******
temporarily_banned: 0
banned: 0

user_id: 30
first_name: Elie
last_name: Helou
username: eliehelou
email: elie@hotmail.com
password: *******
temporarily_banned: 0
banned: 1

user_id: 22
first_name: Jessy
last_name: Helou
username: jessyhelou
email: jessy@hotmail.com
password: *******
temporarily_banned: 0
banned: 1

user_id: 32
first_name: Jad
last_name: Helou
username: jadhelou
email: jad@hotmail.com
password: *******
temporarily_banned: 0
banned: 0

friends_table 示例:

friendship_id | user_id | friend_id | friendship_timestamp
10 20 30 1534342490
9 20 22 1533484062
16 32 20 1541619611

最佳答案

您需要在user 表上添加一个JOIN 来检查 friend 是否被禁止。

您的第一个查询变为:

SELECT * 
FROM users_table u
INNER JOIN friends_table f ON f.user_id = u.user_id
INNER JOIN users_table uf ON uf.user_id = f.friend_id AND uf.banned = 0
WHERE u.user_id = $user_id

对于您的第二个查询:

SELECT * 
FROM users_table u
INNER JOIN friends_table f ON f.friend_id = u.user_id
INNER JOIN users_table uf ON uf.user_id = f.user_id AND uf.banned = 0
WHERE u.user_id = $user_id

也可以将两个查询合并为一个,例如:

SELECT * 
FROM users_table u
LEFT JOIN friends_table f1 ON f1.friend_id = u.user_id
LEFT JOIN users_table uf1 ON uf.user_id = f1.user_id AND uf1.banned = 0
LEFT JOIN friends_table f2 ON f2.user_id = u.user_id
LEFT JOIN users_table uf2 ON uf2.user_id = f2.friend_id AND uf2.banned = 0
WHERE u.user_id = $user_id AND COALESCE(uf1.id, uf2.id) IS NOT NULL

PS:如果您只是想查找好友的计数,您可以使用SELECT COUNT(*) 而不是SELECT *

关于mysql - 表 JOIN 没有像在 mysql 中应该的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54021409/

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