任何人都知道如何将记录与同一组分组,但是下一行该组名称在PHP / MySQL中为空,例如:
在数据库表上记录:
| id | group_title | item | qty | price
| 1 | G-01 | Mouse | 1 | $5
| 2 | G-01 | Keyboard | 1 | $12
| 3 | G-01 | Keyboard | 1 | $12
| 4 | G-01 | Cable | 1 | $1
| 5 | G-02 | Headset | 1 | $20
预期结果:
| Group | Item Name | Qty | Price/qty | Price Total/item | Price Total/group
| G-01 | Mouse | 1 | $5 | $5 | $30
| | Keyboard | 2 | $12 | $24 |
| | Cable | 1 | $1 | $1 |
| G-02 | Headset | 1 | $20 | $20 | $20
我已经尝试了很多天,但仍然没有解决。 预先感谢。
答案 0 :(得分:2)
您可以使用简单的 IF 和 uservar 来完成此查询:
SELECT
IF(g.gname = @myg, '', @myg:= gname) AS gname,
g.mytext
FROM grouptab g
CROSS JOIN ( SELECT @myg:='') AS init
ORDER BY g.gname;
样品
MariaDB [test]> select * from grouptab;
+----+-------+---------+
| id | gname | mytext |
+----+-------+---------+
| 1 | G01 | Name 1 |
| 2 | G01 | Name 2 |
| 3 | G02 | Name 88 |
| 4 | G02 | Name 99 |
| 5 | G01 | Name 4 |
+----+-------+---------+
5 rows in set (0.000 sec)
MariaDB [test]> SELECT
-> IF(g.gname = @myg, '', @myg:= gname) AS gname,
-> g.mytext
-> FROM grouptab g
-> CROSS JOIN ( SELECT @myg:='') AS init
-> ORDER BY g.gname;
+-------+---------+
| gname | mytext |
+-------+---------+
| G01 | Name 1 |
| | Name 2 |
| | Name 4 |
| G02 | Name 88 |
| | Name 99 |
+-------+---------+
5 rows in set (0.000 sec)
MariaDB [test]>