2017-07-02 157 views
-1

我有一個查詢,其中一個LEFT JOIN工作正常。然而,當我將第二個LEFT JOIN添加到第一個表中每個字段具有多個記錄的表中時,我得到了兩個表中的結果的產品,即書籍x發佈者返回。我怎樣才能防止這種情況發生?MYSQL:處理多個LEFT JOIN

SELECT a.*,b.*,p.*, group_concat(b.id as `bids`) 
    FROM authors `a` 
    LEFT JOIN books `b` 
    ON b.authorid = a.id 
    LEFT JOIN publishers `p` 
    on p.authorid = a.id 
    GROUP by a.id 

編輯:

想通了。做到這一點的方法是使用子查詢作爲this answer

SELECT u.id 
    , u.account_balance 
    , g.grocery_visits 
    , f.fishmarket_visits 
FROM users u 
LEFT JOIN (
    SELECT user_id, count(*) AS grocery_visits 
    FROM grocery 
    GROUP BY user_id 
    ) g ON g.user_id = u.id 
LEFT JOIN (
    SELECT user_id, count(*) AS fishmarket_visits 
    FROM fishmarket 
    GROUP BY user_id 
    ) f ON f.user_id = u.id 
ORDER BY u.id; 
+2

更新您的問題添加一個正確的數據示例和預期結果 – scaisEdge

+0

我更新了問題...任何想法? – user6631314

+0

您的問題不清楚...請添加適當的數據樣本和預期的結果.. – scaisEdge

回答

0

如果你做多的LEFT加入,你的查詢將返回結果的笛卡爾乘積。爲了避免這種情況並只獲得你需要的字段的副本,請爲你想要加入的每個表做一個子查詢,如下所示。希望這有助於未來的人。

SELECT u.id 
    , u.account_balance 
    , g.grocery_visits 
    , f.fishmarket_visits 
FROM users u 
LEFT JOIN (
    SELECT user_id, count(*) AS grocery_visits 
    FROM grocery 
    GROUP BY user_id 
    ) g ON g.user_id = u.id 
LEFT JOIN (
    SELECT user_id, count(*) AS fishmarket_visits 
    FROM fishmarket 
    GROUP BY user_id 
    ) f ON f.user_id = u.id 
ORDER BY u.id;