简体   繁体   English

将两个SQL选择查询合二为一

[英]Two sql select queries into one

I have one select query like this, in a table where only the message id, author and recipient are stored: (I want to get all the message_id's) 我有一个这样的选择查询,在一个表中仅存储消息ID,作者和收件人:(我想获取所有message_id)

SELECT message_id FROM messages_to WHERE author_id=0

With this list of message_id's, I want to SELECT in another table to get the actual messages: 有了这个message_id的列表,我想在另一个表中进行SELECT以获得实际的消息:

SELECT messages FROM messages WHERE message_id=(message_id_from_before)

Both queries can return multiple results. 这两个查询都可以返回多个结果。

Is it possible to have one single query which returns the result of the second SELECT query? 是否可以有一个查询返回第二个SELECT查询的结果? Unfortunately I don't have the requirement knowledge to do that; 不幸的是,我没有做到这一点的知识。 if someone could give me a small tip to do this I would be incredibly grateful. 如果有人可以给我一个小提示,我将非常感激。

You can use a subquery in your condition: 您可以根据情况使用子查询:

SELECT messages FROM messages WHERE message_id IN (
  SELECT message_id FROM messages_to WHERE autor_id=0
)

You can use join to get the result from both the table, as you mentioned message_id in both the table. 您可以使用join从两个表中获取结果,就像您在两个表中都提到了message_id一样。

Try this 尝试这个

SELECT messages.message FROM messages 
Inner Join message_id on message_id.message_id = messages.message_id
WHERE message_id.author_id = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM