我遇到了SQL语句的问题。无法理解MySQL中的多表交互。
所以我有两张桌子:
这是我的users
表格:
这是我的messages
表格:
我想要做的是生成一个基本上显示的表:
如果我是用户1
Daniel - Melbourne University
如果我向他发送了一条消息,或者从他那里收到了一条消息,我只希望他的名字出现。
完全失去了如何做到这一点,任何想法?
非常感谢!
答案 0 :(得分:1)
有几种方法。
SELECT
users.*
FROM
users
INNER JOIN
(
SELECT DISTINCT messages_senderid AS user_id FROM messages WHERE messages_receiverid = 1
UNION
SELECT DISTINCT messages_receiverid AS user_id FROM messages WHERE messages_senderid = 1
)
contacts
ON users.users_userid = contacts.user_id
或许......
SELECT
users.*
FROM
users
WHERE
EXISTS (SELECT * FROM messages WHERE messages_senderid = users.users_userid AND messages_receiverid = 1)
OR EXISTS (SELECT * FROM messages WHERE messages_receiverid = users.users_userid AND messages_senderid = 1)
答案 1 :(得分:0)
SELECT users_name,users_university
FROM users
WHERE users_userid IN (SELECT messages_senderid
FROM messages WHERE messages_receiverid=1)
OR users_userid IN (SELECT messages_receiverid
FROM messages WHERE messages_senderid=1)
另一种方法
SELECT users_name,users_university
FROM users
WHERE users_userid IN ( SELECT
CASE WHEN messages_receiverid=1 THEN messages_senderid
WHEN messages_senderid=1 THEN messages_receiverid
END
FROM messages
)
答案 2 :(得分:0)
试试这个:
select u.users_name, u.users_university
from users u
where u.users_usersid in(select m.messages_receiverid
from messages m
where m.messages_senderid=1
union
select m.messages_senderid
from messages m
where m.messages_receiverid=1)
答案 3 :(得分:0)
假设:user_id
是给定参数(在您的示例中:1),您可以尝试:
select concat(users_name, ' - ', users_university, ' University')
from users u
where exists (select 1
from messages
where messages_receiverid = :user_id
or messages_senderid = :user_id)
在这种情况下,在子查询中组合exists
和select 1
是一种快速解决方案。