maria db group by id desc with in magic

xpszyzbs  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(339)

尝试在“group by”中获取“order by id desc”以仅获取最后一条评论。当我将“in”与>1个元素一起使用时,它的效果很好,但是有一个元素或没有“in”。我的mariadb版本是10.0.36-mariadb-0ubuntu0.16.04.1 ubuntu16.04。
下面是示例:56-真ID,55假ID

MariaDB [shop]> SELECT `commentsapi_comment`.`id` FROM `commentsapi_comment`
      WHERE (`commentsapi_comment`.`orderid`='6576') GROUP BY orderid DESC;
+-------+
| id    |
+-------+
| 55811 |
+-------+
1 row in set (0.00 sec)

MariaDB [shop]> SELECT `commentsapi_comment`.`id` FROM `commentsapi_comment`
     WHERE (`commentsapi_comment`.`orderid` IN ('6576')) GROUP BY orderid DESC;
+-------+
| id    |
+-------+
| 55811 |
+-------+
1 row in set (0.00 sec)

MariaDB [shop]> SELECT `commentsapi_comment`.`id` FROM `commentsapi_comment`
      WHERE (`commentsapi_comment`.`orderid` IN ('6576','6576')) GROUP BY orderid DESC;
+-------+
| id    |
+-------+
| 56218 |
+-------+
1 row in set (0.00 sec)

MariaDB [shop]> SELECT `commentsapi_comment`.`id` FROM `commentsapi_comment`
      WHERE (`commentsapi_comment`.`orderid` IN ('6576','-1')) GROUP BY orderid DESC;
+-------+
| id    |
+-------+
| 56218 |
+-------+
1 row in set (0.01 sec)

MariaDB [shop]> SELECT `commentsapi_comment`.`id` FROM `commentsapi_comment`
      WHERE (`commentsapi_comment`.`orderid` IN ('6576')) GROUP BY orderid DESC;
+-------+
| id    |
+-------+
| 55811 |
+-------+
1 row in set (0.00 sec)

MariaDB [shop]> SELECT `commentsapi_comment`.`id` FROM `commentsapi_comment`
      WHERE (`commentsapi_comment`.`orderid` IN ('6576','6577')) GROUP BY orderid DESC;
+-------+
| id    |
+-------+
| 56199 |
| 56218 |
+-------+
2 rows in set (0.00 sec)

MariaDB [shop]> SELECT `commentsapi_comment`.`id` FROM `commentsapi_comment`
      WHERE (`commentsapi_comment`.`orderid` IN ('6577')) GROUP BY orderid DESC;
+-------+
| id    |
+-------+
| 55813 |
+-------+
1 row in set (0.01 sec)

谁知道原因呢?

jfgube3f

jfgube3f1#

那是一个无效的用法 GROUP BY . 新版本会对你唾弃。
中有非聚合列时 SELECT (例如, id )那些不在 GROUP BY (只有 orderid ),所选项目是随机选取的。
建议你改变 id

orderid, MIN(id), MAX(id), COUNT(*), GROUP_CONCAT(id)
``` `IN` 只是个小问题,不是原因。
如果你需要所有的栏目 `id` ,你需要在问题中这样说。关于“grouwise max”有很多问答。

相关问题