MySQL:使用两个不同的列日期查询不同的列

时间:2013-04-26 02:44:46

标签: mysql distinct

我从查询中得到以下结果

SELECT DISTINCT user_id, 
                IF(ra.status = 1, created_datetime, 'No record') AS ACTIVATED, 
                IF(ra.status = 0, created_datetime, 'No record') AS DE_ACTIVATED 
FROM   accounts ra 
WHERE  user_id IN ( 12345678 ); 

+----------+---------------------+---------------------+
| user_id  | ACTIVATED           | DE_ACTIVATED        |
+----------+---------------------+---------------------+
| 12345678 | No record           | 2013-04-28 02:32:36 |
| 12345678 | 2013-03-28 02:32:36 | No record           |
+----------+---------------------+---------------------+

我试图只有一行记录,结合激活和去激活。基本上,就像这样。

+----------+---------------------+---------------------+
| user_id  | ACTIVATED           | DE_ACTIVATED        |
+----------+---------------------+---------------------+
| 12345678 | 2013-03-28 02:32:36 | 2013-04-28 02:32:36 |
+----------+---------------------+---------------------+

在构建查询忍者技能时,非常感谢任何帮助。

此致

1 个答案:

答案 0 :(得分:1)

取两个条件的MAX,但将“false”条件评估为null。然后将其打包在COALESCE中,以便如果计算出的MAX为空,则会将其替换为no record

SELECT user_id,
  COALESCE(MAX(IF(ra.status = 1, created_datetime, null)), 'No record') AS Activated,
  COALESCE(MAX(IF(ra.status = 0, created_datetime, null)), 'No record') AS Deactivated
FROM accounts ra
WHERE user_id IN (12345678)

如果您要查询多个用户,请将其添加到结尾:

GROUP BY user_id