简体   繁体   English

MySQL对group_concat()产生的列中的公共数据进行计数

[英]MySQL count the common data in a column resulted from group_concat()

I am trying to find the number of coauthors who are common between certain authors - When the first name and the last name of the authors is the same and one of the authors has no middle name. 我正在尝试查找某些作者之间共有的共同作者的数量-当作者的名字和姓氏相同且其中一位作者没有中间名时。

In such scenarios, we are interested to find the number of coauthors who are common to the author with no middle name with the authors with middle names. 在这种情况下,我们希望找到没有中间名的作者和具有中间名的作者共同的共同作者的数量。

For example, [link] http://www.sqlfiddle.com/#!9/75243/1 例如,[链接] http://www.sqlfiddle.com/#!9/75243/1

In this table, we have authors with multiple middle names but the same first and last names ie, JACK SMITH, JACK A SMITH, JACK B SMITH . 在此表中,我们的作者具有多个中间名,但名字和姓氏相同,即JACK SMITH, JACK A SMITH, JACK B SMITH We are interested to find the number of coauthors common to 我们有兴趣找到共同的共同作者数量

1. JACK SMITH with JACK A SMITH
2. JACK SMITH with JACK B SMITH

The result would include num field result as 结果将包括num字段结果为

JACK A SMITH  1
JACK B SMITH  0

since JACK A SMITH has one coauthor in common with JACK SMITH and JACK B SMITH has no coauthors in common with JACK SMITH . 因为JACK A SMITHJACK SMITH JACK A SMITH有一个共同作者,而JACK B SMITHJACK SMITH没有共同的作者。

You can use COUNT(DISTINCT ...) with multiple columns. 您可以将COUNT(DISTINCT ...)与多列一起使用。 So you can use this to count the different full names without actually having to concatenate them first. 因此,您可以使用它来计算不同的全名,而不必先将它们连接起来。

SELECT s1.fname, s1.mname, s1.lname, s1.name, COUNT(DISTINCT s2.fname, s2.mname, s2.lname) as num
FROM ( SELECT title, fname, mname, lname, CONCAT(fname, ' ',mname, ' ', lname) as name
  FROM sample ) as s1
LEFT JOIN sample AS s2
ON s1.title = s2.title AND s1.fname = s2.fname AND s1.lname = s2.lname AND s1.mname != s2.mname 
WHERE s1.mname != ''
GROUP BY s1.name
ORDER BY s1.lname, s1.fname, s1.mname 

I used a LEFT JOIN rather than JOIN in order to get the rows with zero coauthors. 我使用LEFT JOIN而不是JOIN来获得具有零共同作者的行。

You should just need to add a COUNT ... 您只需要添加一个COUNT ...

SELECT s1.fname, s1.mname, s1.lname, s1.name, GROUP_CONCAT(DISTINCT s2.name) as coauthor, COUNT(DISTINCT s2.name) as num
FROM ( SELECT title, fname, mname, lname, CONCAT(fname, ' ', IF(mname is null, '', CONCAT(mname, ' ')), lname) as name
  FROM sample ) as s1
JOIN ( SELECT title, fname, mname, lname, CONCAT(fname, ' ', IF(mname is null, '', CONCAT(mname, ' ')), lname) as name
  FROM sample ) AS s2
ON s1.title = s2.title AND s1.name != s2.name
GROUP BY s1.name
ORDER BY s1.lname, s1.fname, s1.mname 

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

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