简体   繁体   English

mysql group by选择条件值

[英]mysql group by select with conditional value

In my messages table I have following rows for example, 例如,在我的消息表中,我有以下几行,

|----|---------|--------------|------|
| id | user_id | message      |status|
|====|=========|==============|======|
| 1  |  2      | msgs 11      |  r   |
|----|---------|--------------|------|
| 2  |  3      | msgs 12      |  r   |
|----|---------|--------------|------|
| 3  |  2      | msgs 13      |  r   |
|----|---------|--------------|------|
| 4  |  3      | msgs 14      |  u   |
|----|---------|--------------|------|

Now, I need to know two things for each user_id 现在,我需要为每个user_id知道两件事

  • Whether it has any status u or not. 是否具有u状态。
  • How many messages are there 有多少条信息

For example, a query like below select user_id, status, count(*) as totalMsg from messages group by user_id Would brought me following rows 例如,像下面这样的查询select user_id, status, count(*) as totalMsg from messages group by user_idselect user_id, status, count(*) as totalMsg from messages group by user_id将带给我以下行

| user_id | status| totalMsg |
|=========|=======|==========|
|  2      |   r   |    2     |
|---------|-------|----------|
|  3      |   r   |    2     | 
              ^
              |------> I need this value to be 'u' because user 3 has a message u

My current query doesnt really gurantee that it will look for a u in the status column. 我当前的查询并不能真正保证它将在状态列中查找u Is that possible to do? 那有可能吗? If so how? 如果可以,怎么办?

MAX() will work on this since r is the least value based on the lexicographical order. MAX()将对此起作用,因为r是基于字典顺序的最小值。

SELECT  user_ID,
        MAX(status) status,
        COUNT(*) totalMsg
FROM    messages
GROUP   BY user_ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM