MYSQL - 添加空外键表时没有得到结果

标签 mysql

所以我一直遇到这个问题。

我有一个结构,表明商店位于城市中。

table Stores
store (pk)
city (fk)

获取它们效果很好。 然后我添加 store_info

table store_info
store (pk)
adress
phone
description

所以我们得到这个查询:

SELECT stores.ID, store_info.address, store_info.phone
                        FROM store_info, stores
                        WHERE stores.city = 1
                        AND stores.ID = store_info.storeID

现在,一切正常。 然而,当我添加 FROM store_brands

    SELECT stores.ID, store_info.address, store_info.phone
                        FROM store_info, stores, store_brands, brands
                        WHERE stores.city = 1
                        AND stores.ID = store_info.storeID

最后一个查询未能给我结果,但查询不会失败。

问题是,我将商店与品牌分开存储,并通过关系表(2 个外键)将品牌链接到商店 它看起来很简单:

store_brands
  storeID (fk to stores)
  brandID (fk to brands)

设置的重点(您可能很清楚)是我可以通过使用 GROUP_CONCAT 收集所有品牌。从技术上讲,只要商店在 store_brands 表中至少有 1 个关系,查询就可以完美运行

现在,我想做的是,我想要完全获得该商店,无论它是否有关联品牌。这些相同的品牌也可以通过链条链接(向上 1 级),因此我想收集这两个实例,这意味着即使没有填写任何品牌,我仍然希望商店显示出来。

我不明白为什么 store_brands 中必须有一行才能让简单的选择查询显示出来。有人能帮我解决这个问题吗?我在我的结构中犯了一个大错误吗?

为清楚起见进行编辑: 顺便说一下,这就是整个查询。它工作得很好,但同样,只有当商店确实有与其链接的品牌时才有效:(之前的查询是对出错位置的调试)

SELECT store_info.storeID, store_info.display_name, store_info.address, store_info.phone, GROUP_CONCAT(brands.display_name ORDER BY brands.name) AS brands
                    FROM store_info, brands, stores, store_brands
                    WHERE stores.city = 1
                    AND store_brands.store =  stores.ID
                    AND brands.id = store_brands.brand
                    AND stores.ID = store_info.storeID
                    GROUP BY store_info.storeID
                    ORDER BY store_info.display_name

更新并回答

感谢idg提供的来源,我发现我需要如何用左连接替换我的常规连接,以及这实际上如何返回NULL。

新的工作查询:

SELECT stores.ID, store_info.display_name, store_info.address, store_info.phone, GROUP_CONCAT(brands.display_name ORDER BY brands.name) AS brands
                        FROM store_info, stores
                        LEFT JOIN store_brands ON stores.ID = store_brands.store
                        LEFT JOIN brands ON store_brands.brand = brands.ID
                        WHERE stores.city = 1
                        AND stores.ID = store_info.storeID
                        GROUP BY store_info.storeID
                        ORDER BY store_info.display_name

最佳答案

对于允许空值的情况,使用LEFT JOIN。阅读how joins work here .

关于MYSQL - 添加空外键表时没有得到结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283958/

相关文章:

Php联系表格插入到Mysql

php - 当以相同方式编写查询时,从 3 个表返回不同的结果

php - 错误 : Unknown column 'Array' in 'field list'

sql - 尝试导入转储时出现重复条目​​错误

php - 如何通过点击将数据从一个页面传递到另一个页面

mysql - 包含多个联接的复杂查询未执行右外联接

php - UTF-8 兼容截断函数

mysql - 如何从我的 Spring Boot 应用程序在 mysql 中创建新架构

java - 使用 Spring Batch 将大量数据存储到数据库

php - 将变量从 shell exec 传递到 mysql_query