试试这个:http ://www.sqlfiddle.com/#!2/f6be7/4
select x.Name, COUNT(p.Name)
from
(
SELECT 'JOHN' AS NAME
UNION
SELECT 'PAUL'
) as x
LEFT JOIN Person p ON p.Name LIKE CONCAT('%',x.NAME, '%')
GROUP BY x.Name
样本数据:
create table person
(
name varchar(100)
);
insert into person values
('JOHN LENNON'),
('WINSTON JOHN LENNON'),
('MICHAEL JOHN FOX'),
('PAUL McCartney'),
('SEAN PAUL DATA'),
('GREAT PAUL OF FIRE'),
('ST PAUL OF X');
输出:
NAME COUNT(P.NAME)
JOHN 3
PAUL 4
如果要数 GEORGE,只需在 UNION 上添加即可:
select x.Name, COUNT(p.Name)
from
(
SELECT 'JOHN' AS NAME
UNION
SELECT 'PAUL'
UNION
SELECT 'GEORGE'
) as x
LEFT JOIN Person p ON p.Name LIKE CONCAT('%',x.NAME, '%')
GROUP BY x.Name
输出:
NAME COUNT(P.NAME)
GEORGE 0
JOHN 3
PAUL 4
太糟糕了 MySQL 没有 unnest 功能。使用 Postgresql 更简单:http ://www.sqlfiddle.com/#!1/87c74/5
select x.Name, count(p.Name)
from
unnest(array['John','Paul','George']) as x(Name)
left join Person p ON p.Name ilike concat('%',x.Name, '%')
group by x.Name
您甚至可以直接将服务器端语言中的逗号分隔字符串用于 Postgresql,只需在该逗号分隔字符串周围放置一个大括号:http ://www.sqlfiddle.com/#!1/87c74/17
select x.Name, count(p.Name)
from
unnest('{John,Paul,George}'::text[]) as x(Name)
left join Person p ON p.Name ilike concat('%',x.Name, '%')
group by x.Name
这也适用于 Postgresql,值列表可以直接在查询中使用(而在 MySQL 中,值列表只能在 DDL 上使用):http ://www.sqlfiddle.com/#!1/87c74/9
select x.Name, count(p.Name)
from
(values('John'),('Paul'),('George')) as x(Name)
left join Person p ON p.Name ilike concat('%',x.Name, '%')
group by x.Name
FROM 子句上的值列表也适用于 Microsoft Sql Server:http ://www.sqlfiddle.com/#!3/87c74/3