首页 > 解决方案 > 如何根据 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

有什么想法可能是错误的或如何使其发挥作用?

标签: mysqlphpmyadmin

解决方案


您忘记了查询中的连接条件。这是旧连接语法的最大问题。我已将您的查询转换为正确的显式连接语法并使用别名使查询更具可读性 -

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

推荐阅读