2011-08-25 103 views
0

我有2個表格,1個表格是訂單和另一個表格是order_itemsOrder_items包含來自訂單的order_id的許多記錄。如果訂單中包含某些order_items(例如product_item = 'nameProduct'),我想查詢表格順序。它會排除這些命令的結果。我該怎麼做?mysql查詢 - 排除條目

我目前的查詢是:

select * orders where order_id in (select order_id from order_items where product_item !='nameProduct'); 

這個查詢沒有真正的工作,因爲select order_id from order_items where product_item !='nameProduct'仍然可以選擇具有相同order_id入境,但只是事先有不同的product_item

的感謝!

回答

2
SELECT * 
FROM orders o 
WHERE NOT EXISTS (SELECT * 
        FROM order_items oi 
        WHERE product_item = 'nameProduct' 
          AND oi.order_id = o.order_id) 
+0

性能方面,它的問題,如果你做了'SELECT *'在內部查詢與類似'選擇「X''或其他一些虛擬的價值? – NullUserException

+1

@NullUserException可能不在MySQL中。聽起來像圍繞「COUNT(*)」和「COUNT(1)」的相同論點。 FWIW,我總是在'EXISTS'子查詢中使用'SELECT 1' – Phil

+0

@Null - 不應該這樣做。絕對不會在SQL Server [如此處解釋](http://stackoverflow.com/questions/1221559/count-vs-count1)。子查詢可能會導致一個問題[儘管在MySQL中](http://stackoverflow.com/questions/3417074/why-would-an-in-condition-be-slower-than-in-sql/3417190#3417190) –