[英]How to select all data from one table and records from another table matching data in first selection. All in one query
I have two tables Messages
and Files
.我有两个表
Messages
和Files
。 The Files
table references Messages
through its message_id
foreign key which corresponds to the Messages
's primary key named message_id
as well. Files
表通过其message_id
外键引用Messages
,该外键也对应于Messages
的名为message_id
的主键。 A message entity may or may not have a file but there cannot be a file without a message.消息实体可能有也可能没有文件,但没有消息就不可能有文件。
So I want to select everything in one query.所以我想 select 一次查询中的所有内容。 All the messages and if there is a file for a message then select a file as well.
所有的消息,如果有消息的文件,那么 select 也是一个文件。 As far as I understand the resulting query should look something like this:
据我了解,生成的查询应如下所示:
select * from Messages union select * from Files where message_id = Messages.message_id
unfortunately this simple query is not valid.不幸的是,这个简单的查询无效。 I also tried using joins:
我也试过使用连接:
select * from Messages
left outer join Files on Messages.message_id = Files.message_id
union
select * from Files
left outer join Messages on Messages.message_id = Files.message_id
but it gives me only those messages which have a file.但它只给我那些有文件的消息。 Using subqueries doesn't seem to be a solution.
使用子查询似乎不是解决方案。 So how do I do this?
那么我该怎么做呢?
You want a full outer join here, which SQLite does not directly support.你想要一个完整的外部连接,SQLite 不直接支持。 You may emulate it with a union, along the lines of what you have already tried:
您可以按照您已经尝试过的方式使用联合来模拟它:
SELECT m.*, f.*
FROM Messages m
LEFT JOIN Files f ON m.message_id = f.message_id
UNION ALL
SELECT m.*, f.*
FROM Files f
LEFT JOIN Messages m ON m.message_id = f.message_id
WHERE m.message_id IS NULL;
The key point of your requirement is:您的要求的关键点是:
A message entity may or may not have a file but there cannot be a file without a message
消息实体可能有也可能没有文件,但没有消息就不可能有文件
which is the definition of a LEFT
join of Messages
to Files
:这是
Messages
to Files
的LEFT
join 的定义:
SELECT *
FROM Messages m LEFT JOIN Files f
ON f.message_id = m.message_id;
If you want data from one table and, if it exists, data from another table then why does a simple left outer join not work?如果您想要一个表中的数据,如果它存在,另一个表中的数据那么为什么简单的左外连接不起作用?
select * from Messages
left outer join Files on
Messages.message_id = Files.message_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.