如何正确查询我的朋友表与MySQL的多对多关系?
我正在使用 MySQL 作为数据库构建一个简单的应用程序。我有一个包含不同信息的用户表,但我也有一个朋友表。每个用户都有自己的 ID,发起请求时会在好友表中引用该 ID。
我的朋友表非常简单:
id int NO PRI auto_increment
date datetime NO CURRENT_TIMESTAMP DEFAULT_GENERATED
user_one_id int NO
user_two_id int NO
request_status tinyint NO
我的问题是尝试查询我的表以查找特定用户的朋友时。下面的查询中的两个子查询都可以单独正常工作,但是当我将它们包含在主查询中时,我没有得到任何结果。没有错误,但也没有结果。
如果登录用户的 ID 为 1,则 -
SELECT id, display_name, join_date, profile_image_url
FROM user WHERE id IN
(SELECT user_one_id FROM friend WHERE user_two_id = 1 AND request_status = 1)
AND id IN
(SELECT user_two_id FROM friend WHERE user_one_id = 1 AND request_status = 1);
查询应该考虑任一列中的用户 ID,具体取决于实际发起好友请求的人。
如果这看起来是个愚蠢的问题,我深表歉意,但我们都得学习一下。
如果有任何其他信息有帮助,请告诉我。
I am building a simple application using MySQL as the database. I have a user table with varying information, but I also have a friends table. Each user has it's own ID which is referenced in the friend table when a request is initiated.
My friends table is pretty simple:
id int NO PRI auto_increment
date datetime NO CURRENT_TIMESTAMP DEFAULT_GENERATED
user_one_id int NO
user_two_id int NO
request_status tinyint NO
My issue is when trying to query my table to find a specific user's friends. My two subqueries in the below query both work fine on their own, however when I include them in the main query, I get no results. No errors, but also no results.
If the logged in user's ID is 1, then -
SELECT id, display_name, join_date, profile_image_url
FROM user WHERE id IN
(SELECT user_one_id FROM friend WHERE user_two_id = 1 AND request_status = 1)
AND id IN
(SELECT user_two_id FROM friend WHERE user_one_id = 1 AND request_status = 1);
The query is supposed to account for the user's ID being in either column, depending on who actually initiated the friend request.
I apologize if this seems like a dumb question, but we all gotta learn sometime.
Please let me know if any additional information would help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信,如果您使用 OR 而不是 AND 作为
WHERE
子句中的条件,您的代码将会起作用,但我建议使用EXISTS
来实现更简单的解决方案>:将
?
替换为您要搜索的用户的 id。I believe that your code would work if you used OR instead of
AND
for the conditions in theWHERE
clause, but I propose a simpler solution withEXISTS
:Replace
?
with the id of the user that you want to search.