使用JOIN ..how寫下這個? 因爲這是很慢..IN IN JOIN如何?
SELECT *
FROM table1
WHERE ID IN (SELECT ID
FROM table1
GROUP BY ID
HAVING COUNT(*) = 2
AND MAX(awaiting) = 1)
AND awaiting = 1
所以,我該怎麼寫?
使用JOIN ..how寫下這個? 因爲這是很慢..IN IN JOIN如何?
SELECT *
FROM table1
WHERE ID IN (SELECT ID
FROM table1
GROUP BY ID
HAVING COUNT(*) = 2
AND MAX(awaiting) = 1)
AND awaiting = 1
所以,我該怎麼寫?
SELECT t1.*
FROM table1 AS t1
INNER JOIN
(
SELECT ID
FROM table1
GROUP BY ID
HAVING COUNT(*) = 2
AND MAX(awaiting) = 1
) AS t2 ON t1.ID = t1.ID AND t1.awaiting = t2.awaiting
WHERE t1.awaiting = 1;
這是確切的,我想要的...謝謝...我會接受它作爲答案 –
@ MR.Test - 隨時歡迎您:) –
這裏是join
版本:
SELECT t1.*
FROM table1 t1 join
(SELECT ID
FROM table1
GROUP BY ID
HAVING COUNT(*) = 2 AND MAX(awaiting) = 1
) tsum
on t1.id = tsum.id
WHERE t1.awaiting = 1
我猜awaiting
爲0或1。如果是在你的內部查詢MAX(awaiting) = 1
是因爲多餘的WHERE語句awaiting = 1
此外,在這種情況下,您可以使用以下查詢。
SELECT *
FROM table1 as T1
WHERE
awaiting = 1
AND
(SELECT count(*) FROM table1 WHERE ID=T1.ID)=2
這是更緊湊和更好,謝謝@ MR.Valex –
您需要一個索引而不是查詢重寫。 – Ben
但下面的答案完美,非常快... 300%...任何方式...爲什麼是負面的? –