2011-08-30 258 views
0

我有一個查詢來選擇所選時間段之間的訂單信息。我想包括一個where子句,它將訂單信息限制爲只有1個訂單總額的所有訂單(始終全部)。在LEFT JOIN子查詢中顯示COUNT?

這是我到目前爲止有:

SELECT o.orders_id, o.customers_id, o.customers_name, o.payment_method, o.date_purchased,o.orders_status, o.shipping_status, ot.value 
FROM orders as o 
LEFT JOIN orders_total as ot ON o.orders_id = ot.orders_id 
WHERE date_purchased between '2011-07-30' AND '2011-08-30 23:59:59' 
AND ot.class = 'ot_total' 
AND o.customer_service_id = '' 
OR o.customer_service_id IS NULL 
ORDER BY orders_id DESC 

該查詢給了我所有的訂單在指定的時間段。我需要包含一個子查詢(或類似的東西),它計算所有以前的(通過全部時間)訂單(order_count)BY customers_id。然後在where子句中包含'HAVING order_count < 2'。

這可能嗎?這有意義嗎?

回答

2

就在您添加這個地方靠近:

AND (
    SELECT COUNT(o.id) 
    FROM orders o2 
    WHERE o2.customers_id = o.customers_id 
) < 2 

或者,如果你想返回的訂單計算,你的SELECT子句中添加它,並添加HAVING子句:

SELECT o.orders_id, ..., (
    SELECT COUNT(o.id) 
    FROM orders o2 
    WHERE o2.customers_id = o.customers_id 
) as orders_count 
... 
HAVING orders_count < 2 
+0

這讓它,謝謝! –

+0

這幫了我一個我也有過的問題。感謝您的回答':)' – Biotox