如何在 GROUP BY 中保留重要的列值
这是我的示例数据集:
id | messageread | timestamp
1 | 'yes' | 999
1 | 'yes' | 0
1 | 'no' | 0
我正在这样做:
SELECT *
FROM nvm
GROUP BY id
您会注意到数据集已经是ORDER BY timestamp DESC
正如它应该的那样,MySQL 返回第一行。
我想要的是 MySQL 返回第一行,但在其中一个分组行中使用 messageread='no'
IF messageread='no'
,无论是否通常返回的行是'yes'
或'no'
这对于MySQL来说可能吗?我向自己保证尽可能多地使用 MySQL 而不是 PHP :-) 谢谢!
Here is the example data set i have :
id | messageread | timestamp
1 | 'yes' | 999
1 | 'yes' | 0
1 | 'no' | 0
I'm doing so :
SELECT *
FROM nvm
GROUP BY id
You will note that the data set is already ORDER BY timestamp DESC
As it should, MySQL is returning the first row.
What i'd want is MySQL to return the first row, but with messageread='no'
IF messageread='no'
in one of the grouped rows, no matter if the normally returned row is 'yes'
or 'no'
Is that possible with MySQL? I promised myself to do as much as possible with MySQL and not PHP :-) Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了确保所有行都来自同一列,请执行以下操作:
这将从 table1 中选择最小或最大行。所有列都来自同一行。
如果它不起作用,您需要将
<
更改为>
它已经晚了,我无法测试查询,但它应该可以完成这项工作。警告,前面有反模式
这到处都有臭鸡蛋的味道,但如果你想快速混合搭配,可以这样做:
In order to make sure all rows are from the same column do:
This will select the minimum or maximum row from table1. And all columns will be from the same row.
If it doesn't work you need to change the
<
to a>
it's late here and I cannot test the query, but it should do the job.Warning, antipattern ahead
This has the smell of rotten eggs all over it, but if you want to mix and match fast do:
您需要与 ANY 一起执行 CASE 语句。
注意:你基本上在这里得到一个随机时间戳,你想要 MAX(timestamp) 还是其他什么?
You'll need to do a CASE statement along with ANY.
Note: you're basically getting a random timestamp here, do you want MAX(timestamp) or something?