2013-04-11 73 views
0

我有一個MySQL查詢從多個表中提取數據。其中一個字段是可以在結果中多次出現的customer_id。有沒有一種方法可以將字段附加到結果中,以顯示每個唯一customer_id在結果集中出現的次數?因爲它代表我的查詢如下...計算結果中出現字符串的次數

SELECT customer.customer_id, customer.name, customer.email, Date_format(orders.datetime,'%d-%m-%Y') AS order_date, order_items.order_item_id, order_items.order_id 

FROM order_items, product, orders, customer 

WHERE order_items.product_id = product.product_id AND product.manufacturer = 'Nike' AND order_items.order_id = orders.order_id AND orders.customer_id = customer.customer_id ORDER BY customer_id, order_date 

非常感謝

回答

0

您要添加:在你的選擇 - >COUNT(customer.customer_id)

並添加查詢結束 - >GROUP BY (customer.customer_id)

遊馬Ÿ需要稍微調整查詢 - 或將某些SELECT條款分解爲子查詢以使其起作用。

+0

簡單而有效。感謝您的幫助 – Jules 2013-04-11 12:59:52

+0

不用擔心伴侶 – 2013-04-11 13:01:16

0

其效率低下,但它應該做的工作:

SELECT 
    customer.customer_id, 
    customer.name, 
    customer.email, Date_format(orders.datetime,'%d-%m-%Y') AS order_date, 
    order_items.order_item_id, 
    order_items.order_id, 
    tmp.za_count 
FROM 
    order_items, product, orders, customer 
INNER JOIN (
    SELECT 
     customer.customer_id, 
     COUNT(*) as za_count 

    FROM 
     order_items, product, orders, customer 
    WHERE 
     order_items.product_id = product.product_id 
     AND product.manufacturer = 'Nike' 
     AND order_items.order_id = orders.order_id 
     AND orders.customer_id = customer.customer_id 
    GROUP BY 
     customer.customer_id 
) as tmp 
    ON tmp.customer_id = customer.customer_id 
WHERE 
    order_items.product_id = product.product_id 
    AND product.manufacturer = 'Nike' 
    AND order_items.order_id = orders.order_id 
    AND orders.customer_id = customer.customer_id 
ORDER BY 
    customer_id, 
    order_date 
相關問題