gpt4 book ai didi

sql - 仅按连接表最大值选择行

转载 作者:行者123 更新时间:2023-11-29 18:10:31 25 4
gpt4 key购买 nike

我只想选择 u.classno、u.userno 具有最大 b.enddate 的行。但它不起作用。

select u.classno, u.userno, b.enddate
from libUser u
join book b on b.id = u.bookid
group by u.classno, u.userno
having b.enddate=max(b.enddate) //doesn't works

最佳答案

Here是 MySQL 官方文档中的一篇优秀文章,但那里仅使用标准 SQL,因此它可以应用于您正在使用的任何 RDBMS。

The Rows Holding the Group-wise Maximum of a Certain Column

Task: For each article, find the dealer or dealers with the most expensive price.

This problem can be solved with a subquery like this one:

SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT MAX(s2.price)
FROM shop s2
WHERE s1.article = s2.article);

The preceding example uses a correlated subquery, which can be inefficient (see Section 13.2.10.7, “Correlated Subqueries”). Other possibilities for solving the problem are to use an uncorrelated subquery in the FROM clause or a LEFT JOIN.

Uncorrelated subquery:

SELECT s1.article, dealer, s1.price
FROM shop s1
JOIN (
SELECT article, MAX(price) AS price
FROM shop
GROUP BY article) AS s2
ON s1.article = s2.article AND s1.price = s2.price;

LEFT JOIN:

SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.article = s2.article AND s1.price < s2.price
WHERE s2.article IS NULL;

The LEFT JOIN works on the basis that when s1.price is at its maximum value, there is no s2.price with a greater value and the s2 rows values will be NULL.

关于sql - 仅按连接表最大值选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451500/

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