2017-09-24 27 views
2

我希望选择一个用户参与的消息的表中的所有对话这个查询的工作为:MySQL的ID为等于列别名

select distinct message_conversationID from messages where message_userID = 2 

不过,我当时想反过来提取物给出外键message_conversationID的所有会话标题(来自另一个表)。我尝试这样做:

select conversation_titles from conversations having conversation_id = 
(select distinct message_conversationID as temp from messages where message_userID = 2) 

但是,看来我无法验证其ID与多行数据等于。我还有什么可以在别名列中提取所有带有ID的标题?

回答

1

如果你想有不同的conversation_title,你可以在用户无论是与(推荐)现有查询或JOIN query

随着IN query匹配IN query,您的查询应该是这样的:

select distinct conversation_titles from conversations where conversation_id IN 
(select message_conversationID from messages where message_userID = 2) 

JOIN query,可以做类似的操作:

select distinct conversation_titles from conversations c inner join 
    messages m on c.conversation_id = m.message_conversationID 
where m.message_userID = 2 

我会推荐第二个查询在你的情况下使用,因为它比第一个查询更有效。