【问题标题】:Combining two MySQL tables yet want one column to equal another组合两个 MySQL 表但希望一列等于另一列
【发布时间】:2017-02-28 23:52:19
【问题描述】:

我正在尝试在一个视图中将两个表连接在一起。我的第一个表结合了两个表,但现在我试图将该表连接到第二个表。我正在尝试使用连接来确保包含用户执行的角色的第二个表与第一个表匹配,但如果第二个表中没有记录,我仍然想要表 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 中的行匹配

【问题讨论】:

标签: php mysql join


【解决方案1】:

只需使用 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 的更多详细信息。

【讨论】:

    【解决方案2】:

    使用LEFT JOIN。 LEFT JOIN 关键字返回左表 (table1) 中的所有行,以及右表 (table2) 中的匹配行。当没有匹配时,右侧的结果为 NULL。 只需将您的 CROSS JOIN 替换为 LEFT JOIN

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多