2013-08-21 149 views
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 

所以,我該怎麼寫?

+0

您需要一個索引而不是查詢重寫。 – Ben

+0

但下面的答案完美,非常快... 300%...任何方式...爲什麼是負面的? –

回答

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; 
+0

這是確切的,我想要的...謝謝...我會接受它作爲答案 –

+0

@ MR.Test - 隨時歡迎您:) –

2

這裏是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 
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 
+0

這是更緊湊和更好,謝謝@ MR.Valex –