MySQL:我需要hel p子查询

时间:2018-03-02 08:51:22

标签: mysql sql subquery

嗨我这个子查询有问题我想知道如果可能的话,如果可能的话,在不使用ORDER BY的情况下对客户有更多保留的客户端.DESC 限制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 个答案:

答案 0 :(得分:0)

试试这个:

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

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

答案 1 :(得分:0)

首先,您编写的查询不需要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
                   );