mysql - 如何根据 ID 从另一个表的单个字段中获取每一行的所有结果
问题描述
我试图在一个字符串中获取每个品牌专门销售的商店的所有名称。
这些是我的表:
Table: tbproduct
+---------+-----------+--------------+------------+--------+----------+
| prod_id | prod_name | prod_brand | prod_price | cat_id | store_id |
+---------+-----------+--------------+------------+--------+----------+
| 1 | Hat1 | Brand1 | 20 | 15 | 1 |
| 2 | Hat2 | Brand2 | 100 | 15 | 1 |
| 3 | Hat3 | Brand3 | 100 | 15 | 2 |
+---------+-----------+--------------+------------+--------+----------+
Table: tbstores
+----------+-------------+
| store_id | store_name |
+----------+-------------+
| 1 | Store1 |
| 2 | Store2 |
+----------+-------------+
这是我目前在 MySQL (PHPMyAdmin) 中使用的代码:
```SQL
SELECT tbproduct.prod_brand as Brand,
concat(min(format(tbproduct.prod_price,0)), ' USD') as Price,
(GROUP_CONCAT(
DISTINCT tbstores.store_name
ORDER BY tbstores.store_name
ASC SEPARATOR ', ')
) as Stores
FROM tbproduct, tbstores
WHERE tbproduct.cat_id = '15'
GROUP BY tbproduct.prod_brand
到目前为止,我得到了包含所有商店名称的单个字符串(名为“商店”的字段):
+----------+-----------+--------------------+
| Brand | Price | Stores |
+----------+-----------+--------------------+
| Brand1 | 20 USD | Store1, Store2 |
| Brand2 | 100 USD | Store1, Store2 |
+----------+-----------+--------------------+
我需要的是获取单个字符串,但仅包含出售品牌的商店的名称:
+----------+-----------+--------------------+
| Brand | Price | Stores |
+----------+-----------+--------------------+
| Brand1 | 20 USD | Store1 |
| Brand2 | 100 USD | Store1, Store2 |
+----------+-----------+--------------------+
您可以在这个 Mysql Fiddle 中找到一个工作示例: https ://www.db-fiddle.com/f/4CxgsQMAeuBGsQ5yLrTXmV/1#&togetherjs=3L1gnCbrA6
有什么想法可能是错误的或如何使其发挥作用?
解决方案
您忘记了查询中的连接条件。这是旧连接语法的最大问题。我已将您的查询转换为正确的显式连接语法并使用别名使查询更具可读性 -
SELECT tp.prod_brand as Brand,
concat(min(format(tp.prod_price,0)), ' USD') as Price,
GROUP_CONCAT(DISTINCT ts.store_name ORDER BY ts.store_name ASC SEPARATOR ', ') as Stores
FROM tbproduct tp
JOIN tbstores ts on tp.store_id = ts.store_id
WHERE tp.cat_id = '15'
GROUP BY tp.prod_brand
推荐阅读
- java - 每当我从 Firebase 加载数据时,RecyclerView 都会滚动到底部
- node.js - ConnectionError: 无法连接到 {database server} - 无法连接(序列)
- javascript - 如何在 JSP 页面中加载远程 JavaScript 文件
- android - 由于异常而停止轮询作业:System.MissingMethodException:UnityEditor.VersionControl.Task
- android - 在android中获取最后一个已知位置
- javascript - 检索网络打印机列表
- c# - 泛型类型的自定义模型绑定
- spring - 无法访问 controller.RestController 以进行 Maven 构建
- git - Git 使用通配符检索配置设置
- ios - UnityWebRequest Post (iOS) 中的 AddBinaryField 总是丢失字节