SQL SQLite 中的 SELECT *, COUNT(*)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3615636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:22:42  来源:igfitidea点击:

SELECT *, COUNT(*) in SQLite

sqlsqlite

提问by grigoryvp

If i perform a standard query in SQLite:

如果我在 SQLite 中执行标准查询:

SELECT * FROM my_table

I get all records in my table as expected. If i perform following query:

我按预期获得了表中的所有记录。如果我执行以下查询:

SELECT *, 1 FROM my_table

I get all records as expected with rightmost column holding '1' in all records. But if i perform the query:

我按预期获得所有记录,最右边的列在所有记录中都保存为“1”。但如果我执行查询:

SELECT *, COUNT(*) FROM my_table

I get only ONE row (with rightmost column is a correct count). Why is such results? I'm not very good in SQL, maybe such behavior is expected? It seems very strange and unlogical to me :(.

我只得到一行(最右边的列是正确的计数)。为什么是这样的结果?我不太擅长 SQL,可能会出现这种行为?这对我来说似乎很奇怪和不合逻辑:(。

回答by nos

SELECT *, COUNT(*) FROM my_tableis not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.

SELECT *, COUNT(*) FROM my_table不是你想要的,也不是真正有效的 SQL,你必须按所有不是聚合的列进行分组。

You'd want something like

你会想要类似的东西

SELECT somecolumn,someothercolumn, COUNT(*) 
   FROM my_table 
GROUP BY somecolumn,someothercolumn

回答by rafaelbattesti

If you want to count the number of records in your table, simply run:

如果要计算表中的记录数,只需运行:

    SELECT COUNT(*) FROM your_table;

回答by Bur?in

count(*)is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

count(*)是一个聚合函数。需要对聚合函数进行分组以获得有意义的结果。您可以阅读:count columns group by

回答by Bob Jarvis - Reinstate Monica

If what you want is the total number of records in the table appended to each row you can do something like

如果您想要的是表中附加到每一行的记录总数,您可以执行以下操作

SELECT *
  FROM my_table
  CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
                FROM MY_TABLE)