简体   繁体   English

使用 PHP 计算 MySQL 中相同行的数量

[英]Count number of identical rows in MySQL with PHP

I have a table in MySql with a list of keywords.我在 MySql 中有一个带有关键字列表的表。 Each keyword was stored in a new row once it was entered by a user on this site.用户在此站点上输入每个关键字后,都会将其存储在新行中。

I have the following query in PHP:我在 PHP 中有以下查询:

SELECT * FROM keywords GROUP BY query

Which gets all the keywords from MySql, and only shows one of each incase of duplicate keywords.它从 MySql 中获取所有关键字,并且只显示每个重复关键字中的一个。 So the output is something like:所以 output 类似于:

Dog
Cat
Lion
Fong

When I'm using $update['query'];当我使用$update['query'];

But I'd like to count how many times each keyword appears in the database, so the output would be, for example:但是我想计算每个关键字在数据库中出现的次数,因此 output 将是,例如:

Dog  (2)
Cat  (3)
Lion (1)
Fong (1)

And I'm trying to figure out what the SQL query should be, and how to print it using PHP.我试图弄清楚 SQL 查询应该是什么,以及如何使用 PHP 打印它。

Try this query:试试这个查询:

SELECT query, COUNT(1) AS rpt_count FROM keywords GROUP BY query

and in PHP you would access the columns using $update['query'] and $update['rpt_count']在 PHP 中,您将使用$update['query']$update['rpt_count']访问列

SELECT *, count(*) as cnt FROM keywords GROUP BY query

Use SELECT *, COUNT(*) AS cnt FROM keywords GROUP BY query .使用SELECT *, COUNT(*) AS cnt FROM keywords GROUP BY query

SELECT *, count(1) FROM keywords GROUP BY query
SELECT query, COUNT(query) FROM keywords GROUP BY query
SELECT keyword, COUNT(*) FROM keywords GROUP BY keyword;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM