从同一表中查询具有不同关系的两个键

时间:2019-01-28 09:26:47

标签: mysql sql

我有一个表,它与另外两个不同的表有2个关系。

User
id_user

Users_Licenses   (one-to-many unidirectional)
user(coach)
license_id

License
id
user_id (user simple) (one-to-one user)

现在,我必须返回用户的用户名(一对一);如果没有用户名,则返回null,但是我不确定该怎么做,因为它总是返回教练的用户名。 我尝试过的:

SELECT ul.license_id, u.username, cl.created_at
FROM user u
INNER JOIN users_licenses ul ON ul.user_id = u.id
INNER JOIN license l ON l.id = ul.license_id
WHERE ul.user_id = :coachId

3 个答案:

答案 0 :(得分:1)

尝试将此LEFT OUTER JOIN回到USER

SELECT ul.license_id, userLicensee.username as licensee
FROM user u
INNER JOIN users_licenses ul ON ul.user_id = u.id_user
INNER JOIN license l ON l.id = ul.license_id
LEFT OUTER JOIN user userLicensee ON l.user_id = userLicensee.id_user
WHERE ul.coachid = :coachId

请注意,我也将WHERE ul.user_id = :coachId更改为ul.coachid = :coachId(您没有为教练用户提及外键列的名称)。

答案 1 :(得分:0)

使用LEFT OUTER JOIN

SELECT ul.license_id, u.username, cl.created_at
FROM users_licenses ul
LEFT OUTER JOIN license l ON l.id = ul.license_id
LEFT OUTER JOIN users u ON ul.user_id = u.id
WHERE ul.user_id = :coachId

答案 2 :(得分:0)

SELECT ul.license_id, u.username, cl.created_at
FROM user u, users_licenses ul, license l
where ul.user_id = u.id 
and  l.id = ul.license_id
and ul.user_id = coachId;

尝试将select语句更改为: