我发现自己想要 选择多个单独的行 (而不是一个组)并在某个字段上连接起来。
鉴于:
假设您有一个产品 ID 及其名称和价格的表格:
+------------+--------------------+-------+
| product_id | name | price |
+------------+--------------------+-------+
| 13 | Double Double | 5 |
| 14 | Neapolitan Shake | 2 |
| 15 | Animal Style Fries | 3 |
| 16 | Root Beer | 2 |
| 17 | Lame T-Shirt | 15 |
+------------+--------------------+-------+
然后你会得到一些花哨的 ajax,将这些小狗列为复选框。
您的 hungry-hippo 用户选择 13, 15, 16
。她今天不吃甜点……
寻找:
一种使用纯 mysql 在一行中总结用户订单的方法。
解决方案:
与 GROUP_CONCAT
IN 子句 the IN
clause :
mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary FROM product WHERE product_id IN (13, 15, 16);
输出:
+------------------------------------------------+
| order_summary |
+------------------------------------------------+
| Double Double + Animal Style Fries + Root Beer |
+------------------------------------------------+
奖金解决方案:
如果您还想要总价,请输入 SUM()
:
mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary, SUM(price) AS total FROM product WHERE product_id IN (13, 15, 16);
+------------------------------------------------+-------+
| order_summary | total |
+------------------------------------------------+-------+
| Double Double + Animal Style Fries + Root Beer | 10 |
+------------------------------------------------+-------+