我有一个mysql查询,它可以获得0或300以上的行总数,它工作正常,除了我需要查询将一些行组合在一起。mysql查询将多个值合并为一个
这里的表:
+------------------------------+---------------------+------------+
| color | check_date | color_code |
+------------------------------+---------------------+------------+
| red | 2017-06-20 13:52:18 | 408 |
| green | 2017-06-17 19:10:25 | 524 |
| green | 2017-06-19 12:17:31 | 314 |
| light-red | 2017-06-19 10:51:05 | 227 |
| dark-green | 2017-06-25 10:47:50 | 82 |
| dark-blue | 2017-06-21 09:23:43 | 0 |
| light-blue | 2017-06-20 09:24:50 | 900 |
| yellow | 2017-06-19 11:01:46 | 833 |
| medium-yellow | 2017-06-07 16:07:49 | 0 |
| medium-red | 2017-06-16 09:46:38 | 19 |
| dark-green | 2017-06-21 08:47:50 | 822 |
| dark-blue | 2017-06-01 15:23:43 | 12 |
| light-blue | 2017-06-22 11:24:50 | 900 |
| yellow | 2017-06-21 09:23:43 | 8 |
| medium-yellow | 2017-06-17 14:07:49 | 11 |
| light-blue | 2017-06-16 09:46:38 | 19 |
+------------------------------+---------------------+------------+
这里的查询:
SELECT color,
max(check_date) AS check_date,
count(*) AS total,
sum(color_code < 1 OR color_code >= 300) AS cnt
FROM check_colors
GROUP BY color
ORDER BY cnt DESC LIMIT 10;
这将返回一个像这样的表:
+------------------------------+---------------------+-------+------+
| color | check_date | total | cnt |
+------------------------------+---------------------+-------+------+
| light-blue | 2017-06-22 11:24:50 | 3 | 2 |
| green | 2017-06-19 12:17:31 | 2 | 2 |
| dark-green | 2017-06-25 10:47:50 | 2 | 1 |
| medium-yellow | 2017-06-17 14:07:49 | 2 | 1 |
| dark-blue | 2017-06-21 08:47:50 | 2 | 1 |
| yellow | 2017-06-21 09:23:43 | 2 | 1 |
| red | 2017-06-20 13:52:18 | 1 | 1 |
| light-red | 2017-06-19 10:51:05 | 1 | 0 |
| medium-red | 2017-06-16 09:46:38 | 1 | 0 |
+------------------------------+---------------------+-------+------+
我需要的是一个MySQL查询相结合以前缀为前缀的浅色,深色和中等颜色。例如,不是将绿色和深绿色分别作为单独的行进行组合,而是将颜色列显示为绿色。结果将是总:4,CNT:3
我需要reults表从上面的查询看起来像这样:
+------------------------------+---------------------+-------+------+
| color | check_date | total | cnt |
+------------------------------+---------------------+-------+------+
| blue | 2017-06-22 11:24:50 | 5 | 3 |
| green | 2017-06-25 10:47:50 | 4 | 3 |
| yellow | 2017-06-21 09:23:43 | 4 | 2 |
| red | 2017-06-20 13:52:18 | 3 | 1 |
+------------------------------+---------------------+-------+------+
检查日期将最近的出光,暗,中等或无前缀的颜色。
如果我在PHP之前或之后在MySQL中这样做会扭曲结果,所以必须在MySQL中。
也许我可以在mysql中以某种方式使用正则表达式?
谢谢:)
为什么它会在查询后“偏斜结果”?你的查询看起来很好;只是首先循环不包含“ - ”的结果来构建颜色列表,然后遍历包含“ - ”的颜色列表并更新关联的“基本颜色”。 –
另一种方法是你在你的GROUP BY子句中进行字符串处理... – CBroe