2012-12-03 172 views
0

我有以下查詢,其中我使用了JOIN s。它說:與連接問題

未知列m.bv ..

請您看看,並告訴我,我做錯了嗎?

$query4 = 'SELECT u.*, SUM(c.ts) AS total_sum1, SUM(m.bv) AS total_sum 
FROM users u 
LEFT JOIN 
(SELECT user_id ,SUM(points) AS ts FROM coupon GROUP BY user_id) c 
ON u.user_id=c.user_id 
LEFT JOIN 
(SELECT user_id ,SUM(points) AS bv FROM matching GROUP BY user_id) r 
ON u.user_id=m.user_id 
where u.user_id="'.$_SESSION['user_name'].'" 
GROUP BY u.user_id'; 
+0

您在查詢中沒有表「m」。 PS請不要使用大寫字母 – poncha

回答

1

您正在使用別名r從表中選擇SUM(points) AS bv,沒有與別名m沒有表。因此,它必須是r.bv,而不是像這樣:

SELECT 
    u.*, 
    SUM(c.ts) AS total_sum1, 
    SUM(r.bv) AS total_sum 
FROM users u 
LEFT JOIN 
(
    SELECT 
     user_id, 
     SUM(points) AS ts 
    FROM coupon 
    GROUP BY user_id 
) c ON u.user_id=c.user_id 
LEFT JOIN 
(
    SELECT 
     user_id, 
     SUM(points) AS bv 
    FROM matching 
    GROUP BY user_id 
) r ON u.user_id = m.user_id 
where u.user_id="'.$_SESSION['user_name'].'" 
GROUP BY u.user_id 
0

替換米,河。查看第二次加入

0

您使用r別名了派生表,並且您使用m引用該表(兩次)。糾正一個或另一個。

既然你組由兩個子查詢user_iduser_id是(我認爲)表user的主鍵,你並不真的需要最後GROUP BY

我會寫這樣的,如果這是針對所有的(許多)用戶:

SELECT u.*, COALESCE(c.ts, 0) AS total_sum1, COALESCE(m.bv, 0) AS total_sum 
FROM users u 
LEFT JOIN 
(SELECT user_id, SUM(points) AS ts FROM coupon GROUP BY user_id) c 
    ON u.user_id = c.user_id 
LEFT JOIN 
(SELECT user_id, SUM(points) AS bv FROM matching GROUP BY user_id) m 
    ON u.user_id = m.user_id 

像這樣在你的(一個用戶)情況:

SELECT u.*, COALESCE(c.ts, 0) AS total_sum1, COALESCE(m.bv, 0) AS total_sum 
FROM users u 
    LEFT JOIN 
    (SELECT SUM(points) AS ts FROM coupon 
     WHERE user_id = "'.$_SESSION['user_name'].'") c 
    ON TRUE 
    LEFT JOIN 
    (SELECT SUM(points) AS bv FROM matching 
     WHERE user_id = "'.$_SESSION['user_name'].'") m 
    ON TRUE 
WHERE u.user_id = "'.$_SESSION['user_name'].'" 

上次查詢也可以簡化爲:

SELECT u.*, 
    COALESCE((SELECT SUM(points) FROM coupon 
       WHERE user_id = u.user_id) 
      , 0) AS total_sum1, 
    COALESCE((SELECT SUM(points) FROM matching 
       WHERE user_id = u.user_id) 
      , 0) AS total_sum 
FROM users u 
WHERE u.user_id = "'.$_SESSION['user_name'].'"