仅在首次购买其他产品时才获得产品?

时间:2014-07-08 18:25:49

标签: mysql sql

我正在查看this example of joining multiple tables并且让我想知道如何在客户表中选择一个名称,例如,在键盘之前购买鼠标?

我正在尝试这样的事情,但没有让它发挥作用。

SELECT 
    product_name, customer.name, date_of_sale 
    FROM sales, product, customer 
    WHERE 
        STR_TO_DATE(
            (
                SELECT date_of_sale 
                FROM sales 
                WHERE product_id = 2
            ),
        STR_TO_DATE('2012-12-23 18:00:00') 

        > 

        STR_TO_DATE(
            (
                SELECT date_of_sale 
                FROM sales 
                WHERE product_id = 3
            ),
        STR_TO_DATE('2012-12-23 18:00:00') 

1 个答案:

答案 0 :(得分:2)

我可以想到两种方法来做到这一点。

方法一是使用Unary JoinSalesSales然后再到Customers)。

方法二是group_concat(或viewtemporary table中的joined to customers

SQLFiddle:http://sqlfiddle.com/#!2/9a031/22

一元加入

我出于提供信息的原因包括所有列。

SELECT c.name,
       s1.product_id AS product1,
       s1.date_of_sale AS date1,
       s2.product_id AS product2,
       s2.date_of_sale AS date2
FROM sales s1,
     sales s2,
     customers c
WHERE s1.date_of_sale < s2.date_of_sale
  AND s1.customer_id = s2.customer_id AND
  c.customer_id = s1.customer_id and
  s1.product_id = 3 AND  s2.product_id = 2;

临时表中的Group_concat

SELECT name
FROM customers,
  (SELECT customer_id,
          group_concat(PRODUCT_ID
                       ORDER BY date_of_sale)
   FROM sales
   GROUP BY customer_id HAVING group_concat(PRODUCT_ID
                                            ORDER BY date_of_sale) LIKE '%3,2%') sales_order
WHERE customers.customer_id = sales_order.customer_id;

优点/缺点

Group Concat:

  • PRO:group_concat方法在类似的行中支持多个值,例如: LIKE '%3,2,10%'
  • CON:对于较小的产品表,它较慢并使用临时的内存表。

加入:

  • PRO:适用于较小的数据量。
  • CON:按顺序要求+1产品加入+1销售表。
  • CON:对于较大的数据大小,可能会慢一些