MySql选择列值唯一的位置

时间:2015-09-14 21:25:23

标签: mysql

我的表people_jobs

+--------+--------+
|  NAME  |  JOB   | 
+--------+--------+
|  John  |  Actor | 
+--------+--------+
|  Jane  | Driver | 
+--------+--------+
|  Bill  |  Actor | 
+--------+--------+
|  John  |  Cook  | 
+--------+--------+

我希望选择名称列唯一的作业参与者的所有名称。这里所需的查询输出只是 Bill

类似的东西:

SELECT name FROM people_jobs WHERE job LIKE "actor" AND COUNT(SELECT * FROM people_jobs WHERE name LIKE name) = 1;

这显然是错误的语法,我无法让GROUP BY工作......想法?

6 个答案:

答案 0 :(得分:3)

为什么选择subselect?

SELECT name, COUNT(*) AS cnt
FROM people_jobs
WHERE job='Actor'
GROUP BY name
HAVING cnt = 1

好的,现在我看到了问题。试试这个:

SELECT name, SUM(JOB='Actor') AS actor_cnt, COUNT(*) as job_cnt
FROM people_jobs
GROUP BY name
HAVING (actor_cnt = 1) AND (job_cnt = 1)

这将弄清楚有多少人是演员,并计算他们有多少工作,并且只返回那些唯一工作的人。

答案 1 :(得分:3)

select name
from people_jobs
where name in (
  select name
  from people_jobs
  group by name
  having count(name) = 1
) and job like 'actor'

这个例子很容易理解,但我喜欢另一个:

SELECT name
FROM people_jobs
GROUP BY name
HAVING COUNT(name) = 1 AND sum(job = 'Actor') = 1

答案 2 :(得分:1)

SELECT name, COUNT(*) c 
FROM people_jobs 
WHERE job = 'Actor' 
GROUP BY name HAVING c = 1

答案 3 :(得分:1)

SELECT DISTINCT x.* 
           FROM people_jobs x 
           LEFT 
           JOIN people_jobs y 
             ON y.name = x.name 
            AND y.job <> x.job 
          WHERE x.job = 'actor' 
            AND y.name IS NULL;

答案 4 :(得分:0)

我会在此上下文中使用NOT EXISTS:

SELECT name
FROM   people_jobs
WHERE  job = 'actor'
       AND NOT EXISTS (SELECT * FROM people_jobs pj
                       WHERE pj.name = people_jobs.name AND pj.job != 'actor')

答案 5 :(得分:-1)

更轻松并解决您的问题:

SELECT distinct name FROM people_jobs WHERE job = "Actor"