[英]SQL - Get elements from two tables, with a third table with all the rows
I am currently trying to create a SQL statement that allows me to retrieve information from two tables, with a third one which has the post_id
from each table and the type. 我当前正在尝试创建一条SQL语句,该语句允许我从两个表中检索信息,第三个语句具有每个表和类型的
post_id
。 This will allow me to know which table the post_id
is from. 这将使我知道
post_id
来自哪个表。
ALL_POSTS: ALL_POSTS:
id PRIMARY KEY,
post_id (FOREIGN KEY)
type
MOVIES: 电影:
post_id
type
title
MUSIC: 音乐:
post_id
type
title
band
This is the SQL statement I used: 这是我使用的SQL语句:
SELECT a.*, b.*, c.* FROM ALL_POSTS as a, MOVIES as b, MUSIC as c WHERE (a.post_id = b.id AND a.type = b.type) OR (a.post_id = c.id AND a.type = c.type)
The problem is that it retrieves a lot of results, and all of them are from the MUSIC table, and most of them are repeated. 问题在于它检索了很多结果,并且所有结果都来自MUSIC表,并且大多数结果都是重复的。
Thanks 谢谢
You should use a LEFT JOIN on both tables. 您应该在两个表上都使用LEFT JOIN 。 This way, it would return all the rows on the ALL_POSTS table and the corresponding details on the MOVIES and MUSIC table.
这样,它将返回ALL_POSTS表上的所有行以及MOVIES和MUSIC表上的相应详细信息。
SELECT * FROM ALL_POSTS AS A
LEFT JOIN MOVIES AS B ON A.post_id = B.post_id AND A.type = B.type
LEFT JOIN MUSIC AS C ON A.post_id = B.post_id AND A.type = C.type
At the moment you are generating a cartesian product from the three tables. 目前,您正在从这三个表生成笛卡尔乘积。 Use
JOIN
s instead: 使用
JOIN
代替:
SELECT A.*, B.*, C.* FROM ALL_POSTS AS A
LEFT JOIN MOVIES AS B ON A.post_id = B.ID AND A.type = B.type
LEFT JOIN MUSIC AS c ON A.post_id = C.ID AND A.type = C.type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.