1

我该怎么做select count(artc_id) as cval, max(srt_id) as maxval, artc_title from table where artc_pub = 1

所以我可以得到如下结果:

       cval | maxval | artc_title | artc_pub
    -----------------------------------------
       4         4     Title 1         1 
                       Title 2         1
                       Title 3         1
                       Title 4         1

我的部分表格如下

artc_id | srt_id | artc_title | artc_pub
-----------------------------------------
   1         1     Title 1         1 
   2         2     Title 2         1
   3         3     Title 3         1
   4         4     Title 4         1
   1         5     Title 1         2
   2         6     Title 2         2

我试过select count(artc_id) as cval, max(srt_id) as maxval, artc_title from table where artc_pub = 1了,但这只给了我一行第一个标题。我想这里肯定不仅仅是一个普通的旧选择。

下面的所有答案都给了我这样的结果:

cval;maxval;artc_title
1   ;     1; Title 1
1   ;     2; Title 2
1   ;     3; Title 3
1   ;     4; Title 4
1   ;     5; Title 5

不像我在问题中提到的那样。

4

5 回答 5

1

我认为最好有 2 个查询,一个用于聚合,一个用于标题:

SELECT COUNT(*) AS cval, 
       MAX(srt_id) AS maxval
FROM table 
WHERE artc_pub = 1 ;

SELECT artc_title 
FROM table 
WHERE artc_pub = 1 ;

您还可以使用该GROUP_CONCAT()函数将标题组合成一行:

SELECT COUNT(*) AS cval, 
       MAX(srt_id) AS maxval,
       GROUP_CONCAT(artc_title ORDER BY srt_id SEPARATOR ', ') 
           AS artc_title  
FROM table 
WHERE artc_pub = 1 ;

您也可以将这两者与连接结合起来,但您将返回大量重复数据:

SELECT ag . cval, 
       ag . maxval, 
       t  . artc_title 
FROM 
    ( SELECT COUNT(*) AS cval, 
             MAX(srt_id) AS maxval
      FROM table 
      WHERE artc_pub = 1 
    ) AS ag
  CROSS JOIN
    table AS t 
WHERE t.artc_pub = 1 ;

如果 MySQL 曾经获得窗口函数(乐观主义者阅读:何时获得),上面的代码将被写成:

SELECT COUNT(*) OVER ()    AS cval, 
       MAX(srt_id) OVER () AS maxval, 
       artc_title 
FROM table 
WHERE artc_pub = 1 ;
于 2012-11-13T16:01:36.377 回答
0

您应该可以在GROUP BY此处使用“文章标题”对结果进行分组:

SELECT
    COUNT(artc_id) AS cval,
    MAX(srt_id) AS maxval,
    artc_title
FROM
    table
WHERE
    artc_pub = 1
GROUP BY
    artc_title
ORDER BY
    artc_title;
于 2012-11-13T13:48:53.950 回答
0

GROUP BY artc_title像这样:

select 
  count(artc_id) as cval, 
  max(srt_id) as maxval, 
  artc_title 
from table 
where artc_pub = 1
GROUP BY artc_title
于 2012-11-13T13:49:01.510 回答
0

你错过了你的分组术语

 SELECT count(artc_id) AS cval, max(srt_id) AS maxval, artc_title 
       FROM table
       WHERE artc_pub = 1
       GROUP BY artc_title
于 2012-11-13T13:49:21.633 回答
0

你试过了吗>>

select count(artc_id) as cval, max(srt_id) as maxval, artc_title from table where artc_pub = 1 Group By artc_title

我希望这会奏效。

于 2012-11-13T13:51:30.930 回答