簡體   English   中英

MySQL查詢以獲取所有產品及其類別

[英]MySQL query to fetch all products and its category

我正在嘗試獲取產品,並將相關類別作為逗號分隔的列表。 以下是我嘗試過的方法,但僅返回1種產品。 我嘗試了LEFT和LEFT OUTER連接,但是都沒有用。 有任何想法嗎?

SELECT 'U' as ACTION
       , product_id
       , GROUP_CONCAT(PC.category_id SEPARATOR ', ') as Categories 
FROM   Products P LEFT JOIN Product_Category PC 
           ON PC.product_id = P.product_id

添加分組依據

SELECT 'U' as ACTION, product_id, GROUP_CONCAT(PC.category_id SEPARATOR ', ')     as Categories 
FROM Products P LEFT JOIN Product_Category PC 
ON PC.product_id = P.product_id group by P.product_id;

-----------------示例-----------

select * from calls;
+----+------------+---------+
| id | date       | user_id |
+----+------------+---------+
|  1 | 2016-06-22 |       1 |
|  2 | 2016-06-22 |    NULL |
|  3 | 2016-06-22 |    NULL |
|  4 | 2016-06-23 |       2 |
|  5 | 2016-06-23 |       1 |
|  6 | 2016-06-23 |       1 |
|  7 | 2016-06-23 |    NULL |
+----+------------+---------+
7 rows in set (0.03 sec)

mysql> select * from payments;
+----+------------+---------+-------+
| id | date       | user_id | value |
+----+------------+---------+-------+
|  1 | 2016-06-22 |       1 |    10 |
|  2 | 2016-06-22 |       3 |    15 |
|  3 | 2016-06-22 |       4 |    20 |
|  4 | 2016-06-23 |       2 |   100 |
|  5 | 2016-06-23 |       1 |   150 |
+----+------------+---------+-------+
5 rows in set (0.00 sec)

mysql> select c.user_id,group_concat(p.value) from calls c inner join payments p on p.user_id=c.user_id group by c.user_id;
+---------+-----------------------+
| user_id | group_concat(p.value) |
+---------+-----------------------+
|       1 | 10,150,10,150,10,150  |
|       2 | 100                   |
+---------+-----------------------+
2 rows in set (0.00 sec)

GROUP_CONCAT函數是一個聚合函數,並且正在使用GROUP BY子句。 如果SELECT語句中沒有GROUP BY ,則它將使用所有找到的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM