Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

select duplicated record and count record from comma separated in mysql

I need a query to select duplicate records and count the total duplicate records,

Posted Records


PostID | Location

  1    | Delhi,Mumbai,Patna
  2    | Mumbai,Noida
  3    | Delhi
  4    | Mumbai,Noida

I would like this result

  Location  | Total
  Delhi     | 2
  Mumbai    | 3
  Patna     | 1
  Noida     | 2
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First thing is you should normalize your structure get rid of comma separated values and use another table to relate your locations with your posts table see Database normalization,for you current structure what you can do is get all locations from your table and insert them into new table then use aggregate function on your new table

CREATE TABLE locaions (cities CHAR(255)) ;

SET @S1 = CONCAT(
  "INSERT INTO locaions (cities) VALUES ('",
  REPLACE(
    (SELECT 
      GROUP_CONCAT(`Location`) AS DATA 
    FROM
      `posts`),
    ",",
    "'),('"
  ),
  "');"
) ;

PREPARE stmt1 FROM @s1 ;

EXECUTE stmt1 ;

This will insert all the locations with repeated data in location table and then use below query to get your desired count

SELECT cities,count(*) 
FROM locaions 
group by cities

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...