计算字符串在结果中出现的次数

时间:2013-04-11 12:36:54

标签: mysql

我有一个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 

非常感谢

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:0)

您想在SELECT中添加: - > COUNT(customer.customer_id)

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

您可能需要在某种程度上调整查询 - 或者将某些SELECT条款分解为子查询以使其生效。