代码之家  ›  专栏  ›  技术社区  ›  Mohamed A.B

MySQL:我需要hel p子查询

  •  0
  • Mohamed A.B  · 技术社区  · 6 年前

    您好,我对这个子查询有一个问题,我想知道的是,如果可能的话,对他们的名字有更多保留的客户,而不使用ORDER BY。。描述 限值1;

    我有以下代码:

    SELECT  c.client_id, COUNT(r.reserva_id)
        FROM reserves r
    INNER JOIN clients c ON c.client_id = r.client_id
    GROUP BY c.client_id
    HAVING COUNT(r.reserva_id) < (SELECT COUNT(r2.reserva_id) 
                            FROM reserves r2
                         GROUP BY r2.client_id)
    

    但它不起作用。你能帮助我吗

    谢谢

    2 回复  |  直到 6 年前
        1
  •  1
  •   cdaiga    6 年前

    尝试以下操作:

    -- WITH ORDER BY COUNT(r.reserva_id) DESC LIMIT 1
    SELECT  c.client_id, COUNT(r.reserva_id) `count`
    FROM reserves r
    INNER JOIN clients c ON c.client_id = r.client_id
    GROUP BY c.client_id
    ORDER BY 2 DESC
    LIMIT 1;
    
    -- WITH SUB QUERIES
    SELECT B.*
    FROM
    (SELECT  c.client_id, COUNT(r.reserva_id) `count`
    FROM reserves r
    INNER JOIN clients c ON c.client_id = r.client_id
    GROUP BY c.client_id) B WHERE B.`count`=
    (SELECT MAX(A.`count`)
    FROM
    (SELECT  c.client_id, COUNT(r.reserva_id) `count`
    FROM reserves r
    INNER JOIN clients c ON c.client_id = r.client_id
    GROUP BY c.client_id) A);
    

    看到了吗 run on SQL Fiddle .

    对我来说,只需执行第一个查询,它很容易理解和运行。

        2
  •  1
  •   Gordon Linoff    6 年前

    首先 join 对于您编写的查询不是必需的。

    第二,我可以把你的问题理解为“最有保留的客户”。当前查询中的逻辑与此不符。

    但对于此版本的查询,它将是:

    SELECT  r.client_id, COUNT(*)
    FROM reserves r
    GROUP BY r.client_id
    HAVING COUNT(*) = (SELECT COUNT(*) 
                       FROM reserves r2
                       GROUP BY r2.client_id
                       ORDER BY COUNT(*) DESC
                       LIMIT 1
                      );
    

    如果你真的想避免 ORDER BY / LIMIT 1 在子查询中,可以执行以下操作:

    SELECT  r.client_id, COUNT(*)
    FROM reserves r
    GROUP BY r.client_id
    HAVING COUNT(*) = (SELECT MAX(cnt)
                       FROM (SELECT COUNT(*) 
                             FROM reserves r2
                             GROUP BY r2.client_id
                            ) r2
                       );