我目前正在尝试创建一个 SQL 语句,该语句允许我从两个表中检索信息,第三个表包含每个表的 post_id
和类型。这将使我知道 post_id
来自哪个表。
所有帖子:
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
关于mysql - SQL - 从两个表中获取元素,第三个表包含所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45370638/