我试图在一个视图中连接两个表。我的第一个表合并了两个表,但现在我试图将该表连接到第二个表。我试图使用连接来确保包含由用户执行的角色的第二个表与第一个表匹配,但如果第二个表中没有记录,我仍然希望表1中的所有记录。我知道我的解释有点混乱,所以我的代码如下:
CREATE VIEW `data` AS SELECT
`information`.`username`, `information`.`department`,
`information`.`company`, `information`.`title`,
`information`.`internal_number` AS `user_internal_phone`,
`information`.`external_number`AS `user_external_phone`,
`information`.`mail`, `information`.`cn` AS `name`, `information`.`hours`,
`information`.`languages`, `information`.`functions`,
`information`.`service` AS `contact_point_name_one`,
`information`.`subservice` AS `contact_point_name_two`,
`information`.`internal_phone` AS `contact_internal_phone`,
`information`.`external_phone` AS `contact_external_phone`,
`information`.`keywords`, `information`.`description`,
`information`.`provided_by`, `information`.`id`,
GROUP_CONCAT(`staff_roles`.`role` SEPARATOR ', ') AS `roles`,
`staff_roles`.`user`
FROM `information`
CROSS JOIN `staff_roles` ON `information`.`username` = `staff_roles`.`user`;
我得到一个错误,当我做一个外部连接和一个交叉连接和一个内部连接都返回行,在两个表中都有一行,但我希望它显示的行,在第二个表中也没有任何东西。使用连接的目的是,当存在匹配时,表2中的行应该与表1
使用LEFT JOIN
。LEFT JOIN关键字返回左表(table1)中的所有行,以及右表(table2)中的匹配行。当没有匹配时,右边的结果为NULL。只需将CROSS JOIN
替换为LEFT JOIN
使用LEFT JOIN代替CROSS JOIN:
CREATE VIEW `data` AS SELECT
...
FROM `information`
LEFT JOIN `staff_roles` ON `information`.`username` = `staff_roles`.`user`;
查看http://www.w3schools.com/sql/sql_join_left.asp了解LEFT JOIN的更多细节