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;
是否有竅門。我只是想創建一個加入的視圖,我不會想到這樣做的子選擇。謝謝。 – user1050499
我意識到我拼寫了'GROUP BY',但現在我想知道它是否有必要... – Neil