Mysql SQL语句作为计数操作的结果创建表?

Mysql SQL语句作为计数操作的结果创建表?,mysql,sql,count,recordset,Mysql,Sql,Count,Recordset,假设你有一张这样的桌子 id terms 1 a 2 c 3 a 4 b 5 b 6 a 7 a 8 b 9 b 10 b 你想得到这样一份报告 terms count a 4 b 5 c 1 所以你在第一张桌子上运行这个 SELECT terms, COUNT( id) AS count

假设你有一张这样的桌子

id   terms    
1    a       
2    c       
3    a       
4    b       
5    b       
6    a       
7    a
8    b
9    b
10   b        
你想得到这样一份报告

terms  count
a      4
b      5
c      1
所以你在第一张桌子上运行这个

SELECT terms, COUNT( id) AS count 
    FROM table 
GROUP BY terms 
ORDER BY terms DESC
到目前为止还不错

但是上面的SQL语句将报表视图放在浏览器上。嗯,我想把数据保存到SQL中

那么,我需要什么SQL命令才能将该报告的结果插入到表中呢

假设您已经创建了一个名为
reports
的表

create table reports (terms varchar(500), count (int))
让我们假设
reports
表是空的,我们只想用下面的视图填充它——用一行代码。我要问的问题是怎么做

  terms  count
    a      4
    b      5
    c      1
就这么简单:

INSERT INTO reports
SELECT terms, COUNT( id) AS count 
FROM table 
GROUP BY terms 
ORDER BY terms DESC
就这么简单:

INSERT INTO reports
SELECT terms, COUNT( id) AS count 
FROM table 
GROUP BY terms 
ORDER BY terms DESC

如果该表已存在:

Insert reports
SELECT terms, COUNT(*) AS count 
FROM table 
GROUP BY terms 
如果没有:

SELECT terms, COUNT(*) AS count 
into reports
FROM table 
GROUP BY terms

如果该表已存在:

Insert reports
SELECT terms, COUNT(*) AS count 
FROM table 
GROUP BY terms 
如果没有:

SELECT terms, COUNT(*) AS count 
into reports
FROM table 
GROUP BY terms

一想到要按特定顺序将数据放入表中,我就畏缩。主要是因为“默认情况下”不保证按该顺序取出数据,所以在选择端需要一个
orderby
语句。一想到按特定顺序将数据推入表中,我就畏缩了。主要是因为“默认情况下”不能保证按该顺序取出数据,因此需要在选择端使用
orderby
语句。