Home > Database > Mysql Tutorial > How to find the string count for a specific id in a column using a MySQL query?

How to find the string count for a specific id in a column using a MySQL query?

王林
Release: 2023-09-01 15:17:07
forward
703 people have browsed it

如何使用 MySQL 查询查找列中特定 id 的字符串计数?

To do this, use the CHAR_LENGTH() function in MySQL. Let us first create a table -

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Subject longtext
   );
Query OK, 0 rows affected (1.17 sec)
Copy after login

Now you can insert some records in the table using insert command-

mysql> insert into DemoTable(Subject) values('MySQL,MongoDB');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Subject) values('MySQL,MongoDB');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement :
mysql> select *from DemoTable;
Copy after login

Output

+----+---------------+
| Id | Subject       |
+----+---------------+
| 1  | MySQL,MongoDB |
| 2  | MySQL,MongoDB |
| 3  | MongoDB       |
| 4  | MySQL         |
+----+---------------+
4 rows in set (0.00 sec)
Copy after login

The following is obtained by pairing the specific id in the column MySQL query to find string count query. Here we check id 1 -

mysql> select Id,char_length(Subject) - char_length(REPLACE((Subject), ',', ''))+1 
   AS FreqSubject from DemoTable WHERE char_length(Subject) > 0 AND Id = 1;
Copy after login

output

+----+-------------+
| Id | FreqSubject |
+----+-------------+
| 1  | 2           |
+----+-------------+
1 row in set (0.02 sec)
Copy after login

The above is the detailed content of How to find the string count for a specific id in a column using a MySQL query?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template