2015-10-12 45 views
0

我有一個搜索結果查詢,我需要修改,以便它不顯示已售出的產品。因此,這裏是不可修改的SELECT語句,因爲它目前存在:2表查詢正確的協議

SELECT id, cid, sid, posttitle, postdetails, city, `state`, zipcode 
FROM posts 
ORDER BY datepublished DESC 

我需要修改,使其看起來到orderdetails table under DetailProductID`以查看它是否存在,如果它現在表現出來;因此,在英語本質上它會是這樣的:

SELECT id, cid, **etc** 
FROM posts 
WHERE posts.id NOT IN orderdetails.DetailProductID 

回答

0
SELECT 
id, cid, sid, posttitle, postdetails, city, state, zipcode 
FROM posts 
where posts.id not in (select DetailProductID from orderdetails) 
ORDER BY datepublished DESC 

,或者使用一個聰明的左連接

SELECT 
posts.id, posts.cid, posts.sid, posts.posttitle, posts.postdetails, posts.city, posts.state, posts.zipcode 
FROM posts 
LEFT JOIN orderdetails ON orderdetails.DetailProductID = posts.id 
where orderdetails.DetailProductID is null 
ORDER BY posts.datepublished DESC 
+0

這是更快的性能明智? –

+0

我會使用左連接,因爲它對大數據的性能會更好。 「NOT IN」條件可能有數百個(如果不是數千個)ID,這會降低速度。從長遠來看,隨着數據的增長,它會進一步降低性能。基本上,對於「IN」聲明中的超過20個項目,我將使用聯接。此外,子查詢通常不會被推薦。 – changepicture

0
SELECT id, cid, etc from posts WHERE posts.id NOT IN (Select DetailProductID from orderdetails)