问题
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
In this table, we have authors with multiple middle names but the same first and last names i.e, 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
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
.
回答1:
You can use COUNT(DISTINCT ...)
with multiple columns. 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.
回答2:
You should just need to add a 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
来源:https://stackoverflow.com/questions/28973941/mysql-count-the-common-data-in-a-column-resulted-from-group-concat