mysql:从子查询中获取两个值

时间:2018-10-06 00:30:27

标签: mysql

我正在尝试使用子查询来检索每个客户的最早订单。我想选择email_addressorder_idorder_date


表格:

客户( customer_id ,电子邮件地址)

订单( order_id ,order_date,customer_id)


我尝试过的操作:

我可以通过这样做得到order_idorder_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列

3 个答案:

答案 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)

JOIN是您的选择。 How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

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;