PHP / MySQL SELECT结果中的某些行在排序时对特定列具有不同的值

时间:2016-08-08 23:45:40

标签: php mysql

对不起,复杂的标题不确定如何最好地解释。

我有以下查询:

SELECT * FROM uc_posts WHERE `postinguser` = 5 AND `id` NOT IN (SELECT dwable FROM uc_redwables WHERE redwabledby = 5) 
UNION ALL 
SELECT * FROM uc_posts WHERE id IN (SELECT dwable FROM uc_redwables WHERE redwabledby = 5) 
ORDER BY time DESC LIMIT 20

表格uc_posts如下所示:

id | postinguser | time                | message |
1        5         2016-08-08 23:50:45      *
2        5         2016-08-08 23:50:35      *
3        5         2016-08-08 23:50:25      *
4        5         2016-08-08 23:50:15      *

表格uc_redwables如下所示:

id | dwable | redwabledby | time                | 
1      3          5         2016-08-08 23:51:15      

输出如下:

   id | postinguser | time                | message |
1        5            2016-08-08 23:50:45      *
2        5            2016-08-08 23:50:35      *
3        5            2016-08-08 23:50:25      *
4        5            2016-08-08 23:50:15      *

我正试图找到一种方法来替换uc_redwables表中所选行的时间,并用它对相应的行进行排序(而不实际更新uc_posts中的那一行)

这样看起来像这样:

   id | postinguser | time                | message |
3        5            2016-08-08 23:51:15      *     //time changed   
1        5            2016-08-08 23:50:45      *
2        5            2016-08-08 23:50:35      *
4        5            2016-08-08 23:50:15      *

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
 p.`id` as id, 
 p.`postinguser` as postinguser,
 p.`message` as message,
 case r.dwable
  when p.id then r.`time`
  else p.`time`
  end as date_time 
FROM `uc_posts` p left join `uc_redwables` r on p.id = r.dwable
WHERE p.`postinguser` = 5 
AND r.redwabledby = 5 
order by date_time desc;

这应该产生如下输出:

   id | postinguser | date_time                | message |
3        5            2016-08-08 23:51:15      *      
1        5            2016-08-08 23:50:45      *
2        5            2016-08-08 23:50:35      *
4        5            2016-08-08 23:50:15      *