MySQL Advance加入

时间:2017-02-11 15:21:03

标签: mysql join count

我最近一直在学习MySQL,并想知道是否有人可以帮我解决这个问题,我正在研究......

我有两张桌子,

首先是departmentTable

+------------+-----------+-----------+-----------+-----------+-----------+-----------+
| Department | Employee1 | Employee2 | Employee3 | Employee4 | Employee5 | Employee6 |
+------------+-----------+-----------+-----------+-----------+-----------+-----------+
| Finance    | Tim C     | Nora C    | Susan P   | Martin S  | Donal D   | Zita P    |
| HR         | Yvonne S  | Marcus F  | Mark B    | Peter S   | Ola G     | Gina P    |
| IT         | John W    | Matt R    | Paul M    | Tom Y     | Jean S    | Martin T  |
+------------+-----------+-----------+-----------+-----------+-----------+-----------+

第二个是employeeDetails表

+--------------+-------+------------+--------+
| EmployeeName | Shift | Employment | Salary |
+--------------+-------+------------+--------+
| Donal D      | Night | Full       | 30000  |
| Gina P       | Night | Part       | 21000  |
| Jean S       | Night | Full       | 30000  |
| John W       | Night | Full       | 24000  |
| Marcus F     | Night | Full       | 21000  |
| Mark B       | Day   | Full       | 23000  |
| Martin S     | Day   | Full       | 23400  |
| Martin T     | Day   | Part       | 31000  |
| Matt R       | Day   | Full       | 22000  |
| Nora C       | Day   | Full       | 22000  |
| Ola G        | Night | Full       | 21400  |
| Paul M       | Day   | Part       | 23000  |
| Peter S      | Day   | Part       | 25000  |
| Susan P      | Day   | Part       | 23000  |
| Tim C        | Day   | Full       | 24000  |
| Tom Y        | Day   | Full       | 23400  |
| Yvonne S     | Day   | Full       | 24000  |
| Zita P       | Night | Part       | 31000  |
+--------------+-------+------------+--------+

我正试图找到一种方法,如果有可能找到一个查询,将查找哪个部门有4天和2夜班员工。所以它应该输出这样的东西..

+------------+-----------+-----------+-----------+-----------+-----------+-----------+
| Department | Employee1 | Employee2 | Employee3 | Employee4 | Employee5 | Employee6 |
+------------+-----------+-----------+-----------+-----------+-----------+-----------+
| Finance    | Tim C     | Nora C    | Susan P   | Martin S  | Donal D   | Zita P    |
| IT         | John W    | Matt R    | Paul M    | Tom Y     | Jean S    | Martin T  |
+------------+-----------+-----------+-----------+-----------+-----------+-----------+

任何帮助表示感谢,我知道这不是存储数据和检索数据的最佳方式,但我正在尝试理解并了解有关MySQL中的连接和计数的更多信息。

2 个答案:

答案 0 :(得分:0)

您应该使用一个表格来存储所有员工的详细信息,并在那里添加一个引用部门的详细信息。切勿在employee1-n中使用您的方法。

同样在我看到Nora C出现在两个部门时,可以看看m-n关系。谷歌是你的朋友

答案 1 :(得分:0)

您应该通过将Employees存储在一列中来修复表结构。

话虽如此,你可以试试这个:

select
    d.*
from departmentTable d
join employeeDetails e on e.EmployeeName in (
    d.Employee1, d.Employee2, d.Employee3,
    d.Employee4, d.Employee5, d.Employee6
)
group by d.department
having sum(e.shift = 'Night') = 2
and sum(e.shift = 'Day') = 4