php - 合并两个 MySQL 表但希望一列等于另一列

标签 php mysql join

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

关于php - 合并两个 MySQL 表但希望一列等于另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40129712/

相关文章:

mysql添加外键错误1215

mysql语法连接两个字段

php - Laravel Pivot 表 Eloquent 关系

php - 在现有网站上有选择地使用 Bootstrap

java - 将嵌套数组从 PHP 传递到 Java servlet

php - 在数据库中存储计算金额的正确方法是什么?

php - X 次尝试失败后阻止登录

从数据库中获取数据的表中包含复选框的 PHP 文件?

php - 多个内部连接在 PHP 中不起作用

mysql - 查询以获取用户最近和最高的事件