![](/img/trans.png)
[英]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.