2011-11-16 115 views
0

我試圖命令分組結果集。問題是其中一個連接條件引用另一個表。具體來說,我需要從table_a中選擇組中具有最高值的記錄,但組標識是不同表中的字段。當連接條件在其他表中時MySQL排除連接

下面是我試過的一些東西,不同的變化。每當我添加GROUP BY pr.id時,知道的一些結果應該排在前3位。當我不添加它時,我每組獲得1個以上的記錄。

任何幫助非常感謝。

SELECT * FROM ivalues AS iv 

INNER JOIN mprod AS p ON (p.id = iv.p_id) 
INNER JOIN contact AS pr ON (pr.id = p.pr_id) 


LEFT OUTER JOIN ivalues i2 
    ON i2.p_id = p2.id 

    AND i2.period = iv.period 
    AND i2.current = iv.current 
    AND i2.cert = iv.cert 
    AND i2.exists = iv.exists 
    AND iv.value > i2.value 
WHERE 
iv.period = 0 
AND iv.current = 1 
AND iv.cert = 1 
AND p.type_id = 15747 
AND iv.exists = 1 
AND i2.id IS NULL 
GROUP BY pr.id 
ORDER BY iv.value ASC 
LIMIT 10; 

SELECT * FROM ivalues AS iv 

INNER JOIN mprod AS p ON (p.id = iv.p_id) 
INNER JOIN contact AS pr ON (pr.id = p.pr_id) 

LEFT OUTER JOIN contact pr2 
    ON pr2.id = p.pr_id 

LEFT OUTER JOIN mprod p2 
    ON p2.type_id = p.type_id   

LEFT OUTER JOIN ivalues i2 
    ON i2.p_id = p2.id 

    AND i2.period = iv.period 
    AND i2.current = iv.current 
    AND i2.cert = iv.cert 
    AND i2.exists = iv.exists 
    AND iv.value > i2.value 
WHERE 
iv.period = 0 
AND iv.current = 1 
AND iv.cert = 1 
AND p.type_id = 15747 
AND iv.exists = 1 
AND i2.id IS NULL 

ORDER BY iv.value ASC 
LIMIT 10; 

SELECT * FROM ivalues AS iv 

INNER JOIN mprod AS p ON (p.id = iv.p_id) 
INNER JOIN contact AS pr ON (pr.id = p.pr_id) 

LEFT OUTER JOIN contact p2 
    ON p2.pr_id = p.pr_id 
    AND p2.type_id = p.type_id 

INNER JOIN mprod p2 
    ON p2.type_id = p.type_id   

INNER JOIN ivalues i2 
    ON i2.p_id = p2.id 

    AND i2.period = iv.period 
    AND i2.current = iv.current 
    AND i2.cert = iv.cert 
    AND i2.exists = iv.exists 
    AND iv.value > i2.value 

WHERE 
iv.period = 0 
AND iv.current = 1 
AND iv.cert = 1 
AND p.type_id = 15747 
AND iv.exists = 1 

ORDER BY iv.value ASC 
LIMIT 3; 

回答

0

我想你會需要加入ivalues和mprod作爲一個子查詢,無論是作爲外連接排除非最大值,或作爲內部組找到的最大值。希望它看起來像這樣:

SELECT * FROM contact 
    INNER JOIN mprod ON mprod.contact_id = contact.id 
    INNER JOIN ivalues ON ivalues.mprod_id = mprod.id 
    LEFT OUTER JOIN (
    SELECT mprod.contact_id, ivalues.* 
     FROM mprod 
     INNER JOIN ivalues ON mprod.id = ivalues.mprod_id 
     WHERE ivalues.period = 0 
     AND ivalues.current = 1 
     AND ivalues.cert = 1 
     AND mprod.type_id = 15747 
     AND ivalues.exists = 1 
) AS pv ON pv.contact_id = contact.id AND pv.value > ivalues.value 
    WHERE ivalues.period = 0 
    AND ivalues.current = 1 
    AND ivalues.cert = 1 
    AND mprod.type_id = 15747 
    AND ivalues.exists = 1 
    AND pv.id IS NULL 
    GROUP BY pr.id 
    ORDER BY iv.value ASC 
    LIMIT 10; 
+0

是否有竅門。我只是想創建一個加入的視圖,我不會想到這樣做的子選擇。謝謝。 – user1050499

+0

我意識到我拼寫了'GROUP BY',但現在我想知道它是否有必要... – Neil