【发布时间】:2017-06-15 13:07:27
【问题描述】:
这是我的桌子:
// 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
【问题讨论】:
-
将第二个查询交叉连接到第一个。