我正在处理问题,无法解决。
我有五个表:
t_employee = {employee_id_pk, fullname, phone, position, passport}
t_facility = {facility_id_pk, direction, title}
t_employee_facility = {emp_fac_id_pk, employee_id_fk, facility_id_fk}
this table is @ManyToMany relationship
between 't_employee' and 't_facility'
t_transport = {transport_id_pk, type}
t_trip = {trip_id_pk, trip_code, employee_id_fk, transport_id_fk}
this table is @ManyToMany relationship between 't_employee' and 't_transport'
我想获得唯一的行 我尝试过这样的事情
SELECT
employee_id, fullname, passport, phone, position, direction, title,
trip_code
FROM
t_facility
INNER JOIN t_employee_facility USING (facility_id)
INNER JOIN t_employee USING (employee_id)
INNER JOIN t_trip USING (employee_id)
GROUP BY
employee_id,
facility_id,
trip_code
共有8个uniquie行。
但是上面的示例给了我18,当我删除trip_id
时我得到了8行,但是
在这种情况下,我会为每个employee_id重复trip_code
个值。
我只想提取不重复的行。我想我应该使用INNER JOIN
来做到这一点,但我不确定。
是否可以联接所有这些表?
谢谢
致谢
答案 0 :(得分:1)
可以使用嵌套联接查询来实现,如下所示:
SELECT B.employee_id, employee_id, fullname, passport, phone,
position,direction, title, trip_code
FROM (SELECT A.employee_id, employee_id, fullname, passport, phone,
position,direction, title
FROM (SELECT employee_id, direction, title FROM t_facility
JOIN t_employee_facility
ON t_facility.facility_id = t_employee_facility.facility_id
) AS A
JOIN employee ON A.employee_id = employee.employee_id) AS B
JOIN t_trip ON B.employee_id = t_trip.employee_id;
答案 1 :(得分:0)
INNER JOIN关键字选择在两个表中都应具有匹配的值。 例如:
SELECT id_pk,information,about
FROM information
INNER JOIN employe ON information.id_pk= employe.id_employe;
是的,您可以在对每个表进行声明时加入您的表。
答案 2 :(得分:0)
如果您只希望各行具有唯一性,但可以,有些员工会显示多个设施或行程,则可以使用DISTINCT
关键字。
SELECT DISTINCT
employee_id,
fullname,
passport,
phone,
position,
direction,
title,
trip_code
FROM t_facility
INNER JOIN t_employee_facility
USING (facility_id)
INNER JOIN t_employee
USING (employee_id)
INNER JOIN t_trip
USING (employee_id);
答案 3 :(得分:0)
您的问题中还有很多不清楚的地方,无论如何我仍会发布。
首先,我在t_employee
子句中看不到表FROM
,因此我不确定此查询是否有效。要获取fullname, passport, phone, position
的列值,您需要将相关的表t_employee
添加到FROM
子句中。
我不太确定JOIN
语法,可以检查MySQL JOINs语法here。
SELECT
employee_id, fullname, passport, phone, position, direction, title,
trip_code
FROM
t_employee
INNER JOIN t_facility USING (facility_id)
INNER JOIN t_employee_facility USING (facility_id)
INNER JOIN t_employee USING (employee_id)
INNER JOIN t_trip USING (employee_id)
GROUP BY
employee_id,
facility_id,
trip_code
如果仍然无法解决问题,您可以尝试进行SELECT DISTINCT
来获取唯一记录,请参见语法here。