选择仅受满足两个标准的记录限制的记录

时间:2009-08-13 16:13:57

标签: mysql

好的,标题令人困惑,但让我解释一下。 假设我有一个员工技能数据库,我希望管理员能够搜索到这些数据库。

经理可能想要搜索具有双节棍技能的员工...... 好的,很好,很容易:

SELECT * FROM skilllist WHERE skillname= "nunchuck"

的Bam!我得到了一份有双节棍技能的员工名单。

但是说经理想要获得一份既有“双节棍”技能又有“弓箭手”技能的员工名单。我该如何创建这样的查询?我不能只说:

SELECT * FROM skilllist WHERE skillname= "nunchuck" AND skillname= "bow staff"

SELECT * FROM skilllist WHERE skillname= "nunchuck" OR skillname= "bow staff"

后者只会让所有员工都拥有双节棍技能,并且所有员工都能获得弓箭技能。我想拥有兼具两种技能的员工。我无法弄清楚。请帮忙! :)

6 个答案:

答案 0 :(得分:1)

select * from employees where 
employeeID in (select memberID from skilllist where skillname = 'nunchuck') and 
employeeID in (select memberID from skilllist where skillname = 'bow staff') 

答案 1 :(得分:0)

已编辑从明显不正确的第一反应,我在阅读帖子时过于迅速。

您可以按员工分组并计算,其中count =您要查找的技能数量。这假设没有技能重复。这是我将用于MSSQL的语法,因此MySQL可能略有不同。

SELECT [EmployeeName], Count(1) FROM 
skilllist 
WHERE skillname in ( "nunchuck","bow staff")
Group By [EmployeeName]
Having Count(1) = 2

答案 2 :(得分:0)

是的,我同意Smandoli。

但是你必须比较id并使用AND子句扩展你的Query-Statement:

SELECT * FROM skilllist WHERE skillname= "nunchuck" AND skillname= "bow staff" AND table1.id=table2.id

答案 3 :(得分:0)

这可行:

Select *
  from employees
 where 1 < (select count(*) 
              from skilllist 
             where slilllist.emp_id = employees.emp_id 
               and skillname in ('nunchuck','bow staff') )

然而,它难以编码技能。因此,如果您现在添加了第三个选项,则必须将1增加到2。

答案 4 :(得分:0)

Select * from employees
RIGHT JOIN skilllist s1 ON s1.memberid = employees.id AND s1.skillname = "nunchuck"
RIGHT JOIN skilllist s2 ON s2.memberid  = employees.id AND s2.skillname = "bow staff"

...

答案 5 :(得分:0)

以下查询将列出具有两种技能组的员工的ID

select employee_id, count(skillname) 
from skilllist 
where skillname in ('nunchuck','bow staff') 
group by employee_id having count(skillname) > 1;