我有两个表,一个用户,另一个有错误。他们有2个关系。用户可以修复或提交错误。我想显示带有提交和修复错误的用户名。
我试过这样的事情:
SELECT usr.username, err.description AS ERROR_SOLVED
FROM Users usr, Errors err
WHERE err.solved_by_id=usr.id
UNION
SELECT usr.username, err.description AS ERROR_SUBMITED
FROM Users usr, Errors err
WHERE err.submited_by_id=usr.id
显然它不起作用,请帮助。
答案 0 :(得分:0)
列必须具有相同的描述。
SELECT usr.username, err.description AS ERROR, 1 as SOLVED
FROM Users usr, Errors err
WHERE err.solved_by_id=usr.id
UNION
SELECT usr.username, err.description AS ERROR, 0 as SOLVED
FROM Users usr, Errors err
WHERE err.submited_by_id=usr.id
会奏效。您还可以定义其他列以显示它的类型。
答案 1 :(得分:0)
像这样......
Select usr.username, submittedErrs.description AS ERROR_SUBMITTED,
fixedErrs.description AS ERROR_SOLVED
from Users usr
left outer join Errors submittedErrs ON submittedErrs.submitted_by_id=usr.id
left outer join Errors fixedErrs ON fixedErrs.solved_by_id=usr.id
答案 2 :(得分:0)
尝试
SELECT usr.username, err.description AS ERROR_SOLVED,
err2.description AS ERROR_SUBMITED
FROM Users AS usr
JOIN Errors AS err ON err.solved_by_id=usr.id
JOIN Errors AS err2 ON err2.submited_by_id=usr.id
答案 3 :(得分:0)
在union中使用别名时,第一个查询确定名称。在后续查询中,不可能对同一字段使用其他别名。
然后,您应该添加一个类型字段以区分错误和解决方案。
如果在没有操作类型的情况下将错误/解决方案放在一起就足够了,我建议在on子句中使用OR进行连接:
SELECT
usr.username,
err.description
FROM
Errors err JOIN Users usr ON err.solved_by_id = usr.id OR err.submited_by_id=usr.id