mysql-有没有其他方法来限制子查询?

fwzugrvs  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(238)

我正在使用mysql。我的table在下面:

create table visit (
   id int,
   seller_number varchar(10),
   date_visit date,
   city_visited varchar(50),
   status varchar(50)
);

此表的示例数据:

id   seller_number  date_visit    city_visited      status

10   11111          2005-02-12    Goiania/GO        Yes
11   11111          2010-05-19    Marilia/SP        Sim
12   11111          2015-01-23    Brasilia/DF       No
13   22222          2014-01-02    Brasilia/DF       Yes
14   22222          2012-10-21    Goiania/GO        No
15   33333          2010-08-09    Marilia/SP        No

我需要一个只返回每个卖家最新日期行的sql,如下所示:

id   seller_number  date_visit    city_visited      status

12   11111          2015-01-23    Brasilia/DF       No
13   22222          2014-01-02    Brasilia/DF       Yes
15   33333          2010-08-09    Marilia/SP        No

我是用subquery来做这个的,但是mysql不接受这个限制:

SELECT seller_number, date_visit, city_visited, status FROM visit WHERE (seller_number, date_visit) IN (SELECT seller_number, MAX(date_visit) FROM visit GROUP BY seller_number LIMIT 500);

它可以无限工作,但我需要限制它,因为表有超过3000万个元组,无法查询。
有没有其他方法可以不在子查询中使用limit来获得这个结果?
谢谢

5tmbdcev

5tmbdcev1#

mysql中有多种方法。你的方法很好,但是 LIMIT 需要进入外部查询:

SELECT v.seller_number, v.date_visit, v.city_visited, v.status
FROM visit v
WHERE (v.seller_number, v.date_visit) IN
       (SELECT v2.seller_number, MAX(v2.date_visit)
        FROM visit v2
        GROUP BY v2.seller_number
       )
LIMIT 500;
pengsaosao

pengsaosao2#

您可以使用存在量词和相关子查询,而不是显式选取最大日期:

SELECT
    v.seller_number
,   v.date_visit
,   v.city_visited
,   v.status
FROM visit v
WHERE NOT EXISTS (
    SELECT *
    FROM visit otherVisit
    WHERE v.seller_number=otherVisit.seller_number
      AND otherVisit.date_visit > v.date_visit
);

相关问题