我有桌子:
ID_table, User, Multi_ID, Action, Date, ...
100 , JN , 0 , test1 , 1.1.2017
101 , DK , 51 , test2 , 3.1.2017
102 , JN , 51 , test2 , 3.1.2017
103 , LP , 0 , test3 , 3.1.2017
104 , DK , 52 , test4 , 5.1.2017
105 , LP , 52 , test4 , 5.1.2017
106 , KH , 52 , test4 , 5.1.2017
我想制作GROUP BY Multi_ID,但仅适用于Multi_ID> 0。 如果Multi_ID = 0 - 没有GROUP BY ...:
Date Users Action
1.1.2017 (JN) test1
3.1.2017 (DK,JN) test2
3.1.2017 (LP) test3
5.1.2017 (DK,LP,KH) test4
我的代码没有解决方案Multi_ID = 0
$sql="SELECT * , GROUP_CONCAT(DISTINCT User separator ',' ) AS Us
FROM table
GROUP BY Multi_ID
ORDER BY Date ASC";
$result = MySQL_Query($sql);
由于
答案 0 :(得分:0)
您需要两个查询,其结果与UNION ALL
:
SELECT date, user AS users, action
FROM mytable
WHERE multi_id = 0
UNION ALL
SELECT
MAX(date) AS date,
GROUP_CONCAT(DISTINCT user SEPARATOR ',' ) AS users,
MAX(action) AS action
FROM mytable
WHERE multi_id > 0
GROUP BY multi_id
ORDER BY date;
另一种选择是在UUID
的情况下按Multi_ID = 0
进行分组,以便将它们分开。这可能更优雅,更不容易理解; - )
SELECT
MAX(date) as date,
GROUP_CONCAT(DISTINCT user SEPARATOR ',' ) AS users,
MAX(action) as action
FROM mytable
GROUP BY CASE WHEN multi_id = 0 THEN uuid() ELSE multi_id END
ORDER BY date;