在我的 MySQL 数据库中,我有表:group
、profile
和 profile_titles
。
这是表 group
的结构:
+----------+----------------+------------+
| group_id | title | profile_id |
| 1 | Group Title 1 | 1 |
| 2 | Group Title 2 | 1 |
| 3 | Group Title 3 | 2 |
| 4 | Group Title 4 | 2 |
| ... | Group Title 1 | ... |
| 20 | Group Title 20 | 12 |
+----------+----------------+------------+
profile_id
链接到表 profile
中的 FK:
+------------+------------------+
| profile_id | profile_title_id |
+------------+------------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| ... | ... |
| 11 | 1 |
| 12 | 5 |
+------------+------------------+
profile_title_id
链接到表 profile_title
中的 FK:
+------------------+-----------------------+
| profile_title_id | title |
+------------------+-----------------------+
| 1 | Profile Title 1 |
| 2 | Profile Title 2 |
| 3 | Profile Title 3 |
| 4 | Profile Title 4 |
| ... | ... |
| 10 | Profile Title 10 |
+------------------+-----------------------+
我在使用JOIN
时遇到了问题。
这是我想要得到的结果:
+----------+----------------+-------------------+-------------------+
| group_id | title | profile_title_id | profile_title |
+----------+----------------+-------------------+-------------------+
| 1 | Group Title 1 | 1 | Profile Title 1 |
| 2 | Group Title 2 | 1 | Profile Title 1 |
| 3 | Group Title 3 | 2 | Profile Title 2 |
| 4 | Group Title 4 | 2 | Profile Title 2 |
| ... | ... | ... | ... |
| 20 | Group Title 20 | 5 | Profile Title 5 |
+----------+----------------+-------------------+-------------------+
但我只得到了我想要得到的前 3 列(group_id
、title
和 profile_title_id
)。如何将 profile_title
添加到我的结果中?我现在的查询:
SELECT
`group`.`group_id`,
`group`.`title`,
`profile`.`profile_title_id`
FROM `group`
LEFT JOIN `profile` ON `group`.`profile_id` = `profile`.`profile_id`
我正在尝试这个查询,但它返回了一个错误(#1066 - 不是唯一的表/别名:'profile'):
SELECT
`group`.`group_id`,
`group`.`title`,
`profile`.`profile_title_id`,
`profile_title`.`title`
FROM `group`
LEFT JOIN `profile` ON `group`.`profile_id` = `profile`.`profile_id`
LEFT JOIN `profile` ON `group`.`profile_id` = `profile`.`profile_title_id`
希望有任何建议,谢谢!
最佳答案
当您应该在第二次左侧加入中加入 profile_title 时,您似乎加入了两次个人资料:
SELECT
`group`.`group_id`,
`group`.`title`,
`profile`.`profile_title_id`,
`profile_title`.`title`
FROM `group`
LEFT JOIN `profile` ON `group`.`profile_id` = `profile`.`profile_id`
LEFT JOIN `profile_title` ON `profile`.`profile_title_id` = `profile_title`.`profile_title_id`
至于您问题中的错误 - 当多次加入同一个表时,您必须 alias表格以区分它们。
请注意,您可以为要从中选择的任何表起别名,基本上它允许在引用表时使用“快捷方式”,或者在查询中有多个同名表时唯一标识表的方法。
表别名可以这样写:
select *
from 'group' as g
在上面的查询中,您可以通过 g
而不是 group
来引用列。
关于mysql - 加入一张 table 2 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32147508/