gpt4 book ai didi

mysql - 如何从左连接中获取前 n 个不同的列值?

转载 作者:行者123 更新时间:2023-11-30 22:08:40 24 4
gpt4 key购买 nike

我想要得到的是“获得前 5 个不同客户的订单 ID 值”。当我将以下查询限制为 5 时,它只会按预期返回前 4 个客户的订单 ID 值。(Around the Horn 有两个不同的订单 ID)有没有办法获得前 5 个不同客户的订单 ID 值?

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;


CustomerName OrderID
Alfreds Futterkiste 10001
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
Around the Horn 10355
Around the Horn 10383
B's Beverages 10289
Antonio baa 10444
.... ....

编辑:我想要得到的是前 5 个不同的客户;

Alfreds Futterkiste                 10001 (first customer)
Ana Trujillo Emparedados y helados 10308 (second customer)
Antonio Moreno Taquería 10365 (third customer)
Around the Horn 10355 (forth customer)
Around the Horn 10383 (forth customer)
B's Beverages 10289 (fifth customer)

在这里are我正在处理的表格。

最佳答案

试试这个。

            SELECT DISTINCT Orders.OrderID, CC.CustomerName

FROM Customers CC
LEFT JOIN Orders
ON CC.CustomerID=Orders.CustomerID
inner join

(
SELECT DISTINCT Customers.CustomerName
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName
LIMIT 5
) C
ON C.CustomerName=CC.CustomerName

ORDER BY CC.CustomerName

关于mysql - 如何从左连接中获取前 n 个不同的列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40860281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com