显示ID从同一属性共享2个值

时间:2014-12-25 16:23:13

标签: mysql sql

我正在尝试从同一属性列中获取掌握2个值(MySQL和Python)的eNum(员工编号),我得到的最接近的是,但是eNum是重复的。我想只获得一次eNum。我想我在WHERE子句中搞砸了......我不知道......

mysql> select * from employee_expert;

+------+---------+
| eNum | package |
+------+---------+
| E246 | Excel   |
| E246 | MySQL   |
| E246 | Python  |
| E246 | Word    |
| E403 | Jave    |
| E403 | MySQL   |
| E892 | Excel   |
| E892 | PHP     |
| E892 | Python  |
+------+---------+




       mysql> SELECT eNum, package 
       FROM employee_expert 
       WHERE (package = 'MySQL' OR package = 'Python') AND (package = 'MySQL' OR    package = 'Python') 
       GROUP BY package;



+------+---------+
| eNum | package |
+------+---------+
| E246 | MySQL   |
| E246 | Python  |
+------+---------+

2 个答案:

答案 0 :(得分:2)

WHERE子句包含条件package = 'MySQL' OR package = 'Python'的不必要重复。使用WHERE (package = 'MySQL' OR package = 'Python')就足够了。或者,为了使其更具可读性,您可以编写WHERE package IN ('MySQL', 'Python')

您的查询会选择了解MySQL' MySQL' ' Python' 或两者

您似乎想要选择知道两者' MySQL' ' Python'。您需要使用JOIN来实现此目的:

SELECT f.eNum
FROM employee_expert f                        # 'f' from 'first'
  INNER JOIN employee_expert s USING(eNum)    # 's' from 'second'
WHERE f.package = 'MySQL'
  AND s.package = 'Python'

不幸的是,如果您需要通过更多语言查找,这种方法的扩展性不会很好。更好的方法是使用原始查询并按eNum对结果进行分组,如下所示:

SELECT eNum, COUNT(DISTINCT package) AS nbLangs
FROM employee_expert
WHERE package IN ('MySQL', 'Python')   # <------------------------------------+
GROUP BY eNum           # Make one entry for each employee                    |
HAVING nbLangs = 2      # Replace '2' with the number of items in this list --+

此查询计算所有知道至少列表中某种语言的员工的已知语言数,然后只保留那些知道所有语言的语言。

答案 1 :(得分:1)

我认为问题在于设计本身,想到它,一个员工可以掌握许多软件包,一个软件包可以被许多员工掌握,它在数据库方面有多对多的关系。例如,将生成一个表employee_package,其中包含一个由每个表的主键组成的主键

+------+------------+
| eNum | package_id |
+------+------------+
| E246 | 1          |
| E246 | 2          |
| E246 | 3          |
| E892 | 1          |
+------+------------+

然后您的请求将是:

SELECT DISTINCT e.eNum from employees e JOIN employee_package ep on ep.eNum = e.eNum 
WHERE ep.package_id = 1 OR ep.package_id = 2
-- let's say that id 1 is for MySQL and id 2 is for Python