在视图中选择count()

时间:2015-04-24 07:42:56

标签: mysql count sql-view

好吧,如果我尝试计算像

这样的视图的总行数
select count(*) from my_view v

它始终返回1,知道视图有很多行。我在mysql文档中找不到任何关于它的文档。如果不可能,是否有解决方法来完成此任务?谢谢。

修改,视图没有主键,然后我也尝试了类似这样的结果1

select count(v.id_customer) from my_view v

以下是一个例子:

mysql> select * from plans limit 5;
+----------------+----------+---------+---------+------------+---------------------+---------------------+----------------+--------------+
| medical_center | customer | invoice | product | recurrence | placed              | due_date            | elapsed_months | elapsed_days |
+----------------+----------+---------+---------+------------+---------------------+---------------------+----------------+--------------+
|              1 |        1 |       1 |       2 |          6 | 2015-01-18 17:16:23 | 2015-07-18 17:16:23 |              2 |           89 |
|              1 |        1 |       3 |       2 |          6 | 2015-04-18 17:16:23 | 2015-10-18 17:16:23 |              5 |            0 |
|              1 |        1 |       4 |       2 |          6 | 2015-04-18 17:16:23 | 2015-10-18 17:16:23 |              5 |            0 |
|              1 |        1 |       5 |       2 |          6 | 2015-04-18 17:16:23 | 2015-10-18 17:16:23 |              5 |            0 |
|              2 |        1 |       6 |       2 |          6 | 2015-04-18 17:16:23 | 2015-10-18 17:16:23 |              5 |            0 |
+----------------+----------+---------+---------+------------+---------------------+---------------------+----------------+--------------+
5 rows in set (0.00 sec)

现在,试着计算:

mysql> select count(*) from plans p;
+----------+
| count(*) |
+----------+
|       1 |
+----------+

3 个答案:

答案 0 :(得分:2)

如果您的视图计算计数,例如

create view my_view as
select count(*) as count from my_table

然后只是:

select * from my_view

视图只返回一行(计数rssult),因此如果选择视图行的计数,当然它将为1.

答案 1 :(得分:1)

反而尝试这样

select count(table_id) as countno from my_view

您将获得正确的值计数

答案 2 :(得分:1)

试试这个:

SELECT * , (select count(*) FROM my_view) AS Cnt FROM my_view

count(*)是一个聚合函数,需要group by子句才能工作。但以上是一种解决方法,可以帮助您。