我有以下表格:
TABLE用户:
id_user | name | job
--------|------|----
1 | John | Director
2 | Lila | Assistant
3 | Paul | Director
4 | Jude | Assistant
表站点:
id_site | city
--------|-------
110 | Paris
111 | London
表联系方式:
id_user | id_site | is_assistant | is_director
--------|---------|--------------|------------
1 | 110 | NULL | 1
2 | 110 | 1 | NULL
3 | 111 | NULL | 1
4 | 111 | 1 | NULL
让我解释一下。我在表Users中有不同的用户;表格中公司的不同位置,最后是表格用户与表格网站相关联的表格。
这是我的问题:
SELECT
site.*,
`assistant`.`job` AS "Assistant Job",`assistant`.`name` AS "Assistant name",
`directors`.`job` AS "Job director",`directors`.`name` AS "Director name"
FROM `site`
LEFT OUTER JOIN contact ON contact.id_site = site.id_site
LEFT OUTER JOIN `users` AS assistant ON `contact`.`id_user` = `assistant`.`id_user` AND `contact`.`is_assistant` = "1"
LEFT OUTER JOIN `users` AS directors ON `contact`.`id_user` = `directors`.`id_user` AND `contact`.`is_director` = "1"
ORDER BY site.id_site
查询很好,但问题是我的结果如下:
id_site | city | Assistant Job | Assistant name | Job director | Director name
--------|--------|---------------|----------------|--------------|--------------
110 | Paris | NULL | NULL | Director | John
110 | Paris | Assistant | Lila | NULL | NULL
111 | London | NULL | NULL | Director | Paul
111 | London | Assistant | Jude | NULL | NULL
我希望在同一行上拥有所有信息,而不是拥有2个几乎相同的行。我喜欢这样的东西:
id_site | city | Assistant Job | Assistant name | Job director | Director name
--------|--------|---------------|----------------|--------------|--------------
110 | Paris | Assistant | Lila | Director | John
111 | London | Assistant | Jude | Director | Paul
我希望我足够清楚。你能帮帮我吗?
非常感谢。
Stefey
答案 0 :(得分:2)
如果您将两个contact
ID放在同一行,它应该有效。问题是,因为它连接到两行,并连接到拆分行。因此,如果您加入联系表两次(使用is_director
和is_assistant
的第二个子句),则每个应该只有1个结果。然后加入各自的users
表。
SELECT
site.*,
`assistant`.`job` AS "Assistant Job",
`assistant`.`name` AS "Assistant name",
`directors`.`job` AS "Job director",
`directors`.`name` AS "Director name"
FROM
`site`
LEFT OUTER JOIN
`contact` AS ContactAssistant
ON ContactAssistant.id_site = site.id_site
AND ContactAssistant.is_assistant = "1" -- Add this clause here
LEFT OUTER JOIN
`contact` AS ContactDirector
ON ContactDirector.id_site = site.id_site
AND ContactDirector.is_director = "1" -- Add this clause here
LEFT OUTER JOIN
`users` AS assistant
ON ContactAssistant.`id_user` = `assistant`.`id_user`
-- AND `contact`.`is_assistant` = "1" -- No longer needed
LEFT OUTER JOIN
`users` AS directors
ON ContactDirector.`id_user` = `directors`.`id_user`
-- AND `contact`.`is_director` = "1" -- No longer needed
ORDER BY site.id_site
不相关,是您的is_assistant
和is_director
字段(TINY)INT
还是VARCHAR
?我假设他们是数字的,所以你可能想确保你这样对待它们。