[英]getting datafrom two tables collectively and get all the rows from table A
[英]SQL - Get elements from two tables, with a third table with all the rows
我当前正在尝试创建一条SQL语句,该语句允许我从两个表中检索信息,第三个语句具有每个表和类型的post_id
。 这将使我知道post_id
来自哪个表。
ALL_POSTS:
id PRIMARY KEY,
post_id (FOREIGN KEY)
type
电影:
post_id
type
title
音乐:
post_id
type
title
band
这是我使用的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)
问题在于它检索了很多结果,并且所有结果都来自MUSIC表,并且大多数结果都是重复的。
谢谢
您应该在两个表上都使用LEFT JOIN 。 这样,它将返回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
目前,您正在从这三个表生成笛卡尔乘积。 使用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.