MySQL:我需要帮助Subquery

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL:我需要帮助Subquery相关的知识,希望对你有一定的参考价值。

嗨,我对这个子查询有一个问题,如果可能的话,我想知道客户对他们的名字有更多的保留而不使用ORDER BY .. DESC LIMIT 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)

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

谢谢..

答案

试试这个:

-- 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

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

另一答案

首先,对于您编写的查询,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
                   );

以上是关于MySQL:我需要帮助Subquery的主要内容,如果未能解决你的问题,请参考以下文章

需要示例代码片段帮助

Mysql join with subquery join 使用相关名称

DEPENDENT SUBQUERY” 和 “SUBQUERY”

MySQL Left Join Subquery with *

MySQL子查询subquery

MySQL - This version of MySQL doesn‘t yet support ‘LIMIT & IN/ALL/ANY/SOME subquery‘