我正在尝试使用子查询来检索每个客户的最早订单。我想选择email_address
,order_id
和order_date
客户( customer_id ,电子邮件地址)
订单( order_id ,order_date,customer_id)
我可以通过这样做得到order_id
或order_date
SELECT email_address,
(SELECT order_date /* or order_id */
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY order_date LIMIT 1)
FROM customers c
GROUP BY email_address;
但是如果我尝试在子查询中执行SELECT order_id, order_date
,则会收到错误消息:
操作数应包含1列
答案 0 :(得分:2)
您可以使用JOIN
来解决此问题,但是需要注意,JOIN
仅适用于给定客户的最旧值:
SELECT c.email_address, o.order_id, o.order_date
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id AND
o.order_date = (SELECT MIN(order_date) FROM orders o2 WHERE o2.customer_id = c.customer_id)
答案 1 :(得分:0)
SELECT o.order_id, c.email_address, o.order_date
FROM customers c
INNER JOIN (
SELECT order_date, order_id, customer_id
FROM orders o
ORDER BY order_date
) as o on o.customer_id = c.customer_id
GROUP BY email_address;
答案 2 :(得分:0)
您可以使用JOIN获得所需的结果,或按如下所示修改查询:
SELECT email_address,
(SELECT order_date
FROM orders o1
WHERE o1.customer_id = c.customer_id
ORDER BY order_date LIMIT 1) as `order_date`,
(SELECT order_id
FROM orders o2
WHERE o2.customer_id = c.customer_id
ORDER BY order_date LIMIT 1) as `order_id`
FROM customers c
GROUP BY email_address;