7

我有这个 SQL 查询:

SELECT id, COUNT(*) AS price
FROM (SELECT * FROM rt WHERE somecondition) AS st
      JOIN tt
      ON st.id = tt.id
GROUP BY id;

现在,我想选择所有表中价格最高的行。我已经尝试过了,不幸的是它根本没有返回任何行:

SELECT id, COUNT(*) AS price
FROM (SELECT * FROM rt WHERE somecondition) AS st
      JOIN tt
      ON st.id = tt.id
GROUP BY id
HAVING price = MAX(price);

我有点迷茫,有人有任何指示吗?

4

6 回答 6

3

这对我来说看起来相当简单:

select * from <table> 
where <column name> in(
   SELECT MAX(column name) FROM table
)
于 2013-05-02T13:18:00.473 回答
1

试试这个解决方案:

SELECT a.id, a.price
FROM
(
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa
    INNER JOIN tt bb ON aa.id = bb.id
    WHERE aa.somecondition
    GROUP BY aa.id
) a
INNER JOIN
(
    SELECT MAX(aa.price) AS maxprice
    FROM
    (
        SELECT COUNT(1) AS price
        FROM rt aaa
        INNER JOIN tt bbb ON aaa.id = bbb.id
        WHERE aaa.somecondition
        GROUP BY aaa.id
    ) aa
) b ON a.price = b.maxprice

编辑:虽然我想不出任何方法来重写它以便不必冗余地编写基本查询,但您可能可以这样做:

SELECT GROUP_CONCAT(a.id) AS ids, a.price
FROM
(
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa
    INNER JOIN tt bb ON aa.id = bb.id
    WHERE aa.somecondition
    GROUP BY aa.id
) a
GROUP BY a.price
ORDER BY a.price DESC
LIMIT 1

这会生成共享相同最大值的 id 的逗号分隔列表。这可能不是您正在寻找的格式,但它避免必须编写两次基本查询的一种方法。只是把它放在那里。

于 2012-07-08T08:37:55.313 回答
0

您要求一种不需要多次说明内部查询的冗余方法。这当然是 cte 的好处。这是为使用该策略而重写的另外两个解决方案。

WITH basequery as (
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa INNER JOIN tt bb ON aa.id = bb.id
    WHERE [aa.somecondition]
    GROUP BY aa.id
)
SELECT a.id, a.price
FROM
    basequery as a INNER JOIN
    (SELECT MAX(price) AS maxprice FROM basequery) as b
        ON a.price = b.maxprice
-- or
WITH basequery as (
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa INNER JOIN tt bb ON aa.id = bb.id
    WHERE [aa.somecondition]
    GROUP BY aa.id
)
SELECT a.id, a.price
FROM
    basequery as a
WHERE
    a.price >= ALL (SELECT price FROM basequery)
于 2012-07-08T17:26:50.707 回答
0

假设@Zane 的答案是您想要的,这里是他的查询的可移植版本,它也避免了 LIMIT/TOP 操作。我对mysql方言不是很熟悉,但我想这会毫无问题地工作。

SELECT a.id, a.price
FROM (
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa
    INNER JOIN tt bb ON aa.id = bb.id
    WHERE [somecondition]
    GROUP BY aa.id
) a
WHERE
    a.price >= ALL (
        SELECT COUNT(1) AS maxprice
        FROM rt aa
        INNER JOIN tt bb ON aa.id = bb.id
        WHERE [somecondition]
        GROUP BY aa.id
    )
于 2012-07-08T08:49:39.260 回答
0

HAVING用于在聚合发生后检查条件。

WHERE在聚合发生之前使用。

SELECT id, COUNT(*) AS price
FROM (SELECT * FROM rt WHERE somecondition) AS st
  JOIN tt
  ON st.id = tt.id
WHERE price = (SELECT MAX(price) FROM ...table)
GROUP BY id
于 2012-07-08T08:17:20.660 回答
0

试试这个,把MAX放在select里,这应该是正确的方法

SELECT id, COUNT(*) AS price, MAX(price) AS max_price
FROM (SELECT some_table_name FROM rt WHERE somecondition LIMIT 1) AS st
      JOIN thenextTable as tt
      ON st.id = tt.id
GROUP BY id;
于 2012-07-08T08:21:50.817 回答