我正在查看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')
答案 0 :(得分:2)
我可以想到两种方法来做到这一点。
方法一是使用Unary Join
(Sales
到Sales
然后再到Customers
)。
方法二是group_concat
(或view
)temporary 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;
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:
LIKE '%3,2,10%'
加入: