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 

非常感谢

4

2 回答 2

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 
于 2013-04-11T12:46:28.550 回答
0

您要添加:在您的 SELECT ->COUNT(customer.customer_id)

并添加查询的结尾 ->GROUP BY (customer.customer_id)

您可能需要稍微调整查询 - 或将某些SELECT术语分解为子查询以使其正常工作。

于 2013-04-11T12:46:43.863 回答