从共享公共字段的4个表中获取数据

时间:2019-04-29 00:00:50

标签: mysql sql

我有这个结构,

表格

employees

id

name
_______________________
entrance

id_employees

day

hour
_______________________
break

id_employees

day

hour
_______________________
break_end

id_employees

day

hour
_______________________
exit

id_employees

day

hour

所以我需要列出每个雇员的注册,其中“ id_employees”等于employees表的“ id”,我设法在两个表上做到了,但是没有办法将它们链接在一起,有什么方法可以做到这一点?

2 个答案:

答案 0 :(得分:0)

您可能会遇到问题,因为所有表都具有相同名称的列,并且它们将在软件的输出数组中相互覆盖。您可以使用列别名来解决此问题:

SELECT e.id, e.name, 
       ee.day AS entrance_day, ee.hour AS entrance_hour,
       b.day AS break_day, b.hour AS break_hour,
       be.day AS break_end_day, be.hour AS break_end_hour,
       ex.day AS exit_day, ex.hour AS exit_hour
FROM employees e
LEFT JOIN entrance ee ON ee.id_employees = e.id
LEFT JOIN break b ON b.id_employees = e.id
LEFT JOIN break_end be ON be.id_employees = e.id
LEFT JOIN exit ex ON ex.id_employees = e.id

请注意,如果员工在特定的一天没有休息,则需要使用LEFT JOIN。在这种情况下,使用INNER JOIN将导致这些员工的输出中没有行。

答案 1 :(得分:0)

最可能的解决方案是通过左联接,尽管您可能需要别名化通用列名以区分它们。 查询的基础是:

SELECT e.*,b.*,be.*,e.* FROM employees e
LEFT JOIN break b ON e.id = b.id_employees
LEFT JOIN break_end br ON e.id = b.id_employees
LEFT JOIN exit ON e.id = id_employees

由于在多个表中具有相似的列名,因此必须在SELECT子句上更具体,以更轻松地区分所需的不同列

喜欢:

SELECT e.id, 
       b.day as break_day, 
       b.hour as break_hour, 
       br.day as break_end_day, 
       br.hour as break_end_hour, 
       ...

依此类推