我知道這個問題已經在這裏問了很多次,但畢竟我找不到我想要的答案。mysql - 正確加入兩個表作爲一對多關係
我的問題是:
我有兩個表,這些表的結構爲:
表1: item_id, store,title,available,shipping
表2: item_id, review_rate,user_id,review_title
這些表格應該作爲one to many
關係加入。
例如,如果這些表中的數據是爲:
table1:
item_id store title available shipping
-------------------------------------------------------
11 glasses ..........................
12 dresses ..........................
.
.
.
table2:
item_id review_rate user_id review_title
--------------------------------------------------
11 3 10023 good item
11 5 10024 nice item
12 1 10024 nice one
.
.
.
那麼結果應該儘可能接合後:
afterJoin:
item_id store title available shipping rate people_reviewed
-----------------------------------------------------------------------
11 .................................... 4 2
12 .................................... 1 1
我試圖加入的query
是:
CREATE OR REPLACE VIEW afterJoin AS
SELECT i.*,round(AVG(r.review_rate)) as rate,count(r.user_id) as people_reviewed
FROM table1 i
RIGHT JOIN table2 r ON i.item_id = r.item_id
但這隻返回一行。
mysql不等於SQL-server – Jens
謝謝你改進我的錯誤 –
爲什麼你在這裏使用正確的連接?爲什麼不是左連接?當您使用正確的連接時,即使table1中的行不存在,您也將獲得所有評論。這可能是好的,但大多數人認爲是另一個方向。你想要所有的項目和他們的評論(如果存在)。你有這種編碼的方式,你不會得到一個項目,如果它沒有審查返回。 –