备用语法以连接多个单独的行
警告:这篇文章会让你饿。
鉴于:
我发现自己想要选择多个单独的行(而不是一组),并连接到某个字段。
假设您有一张产品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,将这些幼犬列为复选框。
饥饿的河马用户选择13, 15, 16
。今天没有甜品给她...
找:
一种使用纯mysql在一行中汇总用户订单的方法。
解:
使用GROUP_CONCAT
与该IN
条款:
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 |
+------------------------------------------------+-------+
PS:很抱歉,如果您附近没有In-N-Out ...