我如何计算总结果并将它们分组?

时间:2017-06-15 13:07:27

标签: mysql sql arrays group-by

这是我的表:

// posts
+----+-----------+--------------------+------------+--------+
| id |   title   |        body        |  author_id | amount |
+----+-----------+--------------------+------------+--------+
| 1  | post1     | somthing           | 2543       | 5000   |
| 2  | post2     | something else     | 4352       | NULL   |
| 3  | post3     | whatever           | 1563       | 1200   |
| 4  | post4     | test context       | 7234       | NULL   |
| 5  | post5     | anything ...       | 4352       | NULL   |
+----+-----------+--------------------+------------+--------+

我也有这两个问题:

SELECT COUNT(*), COUNT(amount) FROM posts
+----------+---------------+
| COUNT(*) | COUNT(amount) |
+----------+---------------+
| 5        | 2             |
+----------+---------------+

SELECT * FROM posts ORDER BY id LIMIT 0,2
+----+-----------+--------------------+------------+--------+
| id |   title   |        body        |  author_id | amount |
+----+-----------+--------------------+------------+--------+
| 1  | post1     | somthing           | 2543       | 5000   |
| 2  | post2     | something else     | 4352       | NULL   |
+----+-----------+--------------------+------------+--------+

现在我想结合这两个查询,这是预期的结果:

+----+-----------+--------------------+------------+--------+----------+---------------+
| id |   title   |        body        |  author_id | amount | COUNT(*) | COUNT(amount) |
+----+-----------+--------------------+------------+--------+----------+---------------+
| 1  | post1     | somthing           | 2543       | 5000   | 5        | 2             |
| 2  | post2     | something else     | 4352       | NULL   | 5        | 2             |
+----+-----------+--------------------+------------+--------+----------+---------------+

我怎样才能实现这一目标?这是我到目前为止所尝试的错误,它总是返回一行:

SELECT x.*, COUNT(*), COUNT(amount)
FROM (
    SELECT * FROM posts ORDER BY id
) x
LIMIT 0,2

3 个答案:

答案 0 :(得分:2)

您可以使用CROSS JOIN执行此操作。像这样:

SELECT 
    posts.*,
    tbl.nbr,
    tbl.nbrAmount 
FROM 
    posts 
CROSS JOIN 
    (SELECT COUNT(*) as nbr, COUNT(amount) as nbrAmount FROM posts) AS tbl
ORDER BY id LIMIT 0,2

答案 1 :(得分:2)

如果我理解你正确的事情。交叉加入查询shoudl做的伎俩..

SELECT * 
FROM posts p
CROSS JOIN (SELECT COUNT(*) cnt, COUNT(amount) cntamt FROM posts) t
ORDER BY p.id 
LIMIT 0,2

ALTERNATE也许(UNTESTED)......但又是一个子查询...但只有1个where子句。

SELECT id, title, body, author_id, max(cnt) cnt, max(cntAmount) cntAmount
FROM (SELECT id
           , title
           , body
           , author_id
           , @cnt=@cnt+1 as cnt
           , case when Amount is not null then @cntamt:=@cntAmt+1 else @cntAmt end as cntAmount
      FROM posts p
      CROSS JOIN (SELECT @cnt:=0,@cntAmt:=0) t
      GROUP BY id, title, body, author_id) Z
ORDER BY z.id 
LIMIT 0,2

答案 2 :(得分:0)

使用加入你可以结合使用。

SELECT p1.*,p2.* FROM posts AS p1
LEFT JOIN (
   SELECT COUNT(*), COUNT(amount) FROM posts
) AS p2 ON 1=1
ORDER BY p1.id LIMIT 0,2