MYSQL - 在两列中选择dISTINCT值

时间:2016-05-10 09:58:13

标签: mysql

我想选择sender_id或receiver_id = 20的最后一次。让我为您提供一个快速示例。

    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("text/plain");
    String shareBody = "Enter your link here";
    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    startActivity(Intent.createChooser(sharingIntent, "Open via"));

2 个答案:

答案 0 :(得分:0)

这样的事情:

SELECT LEAST(sender_id, receiver_id), 
       GREATEST(sender_id, receiver_id),
       MAX(created_time)
FROM mytable
WHERE 20 IN (sender_id, receiver_id)
GROUP BY LEAST(sender_id, receiver_id), 
         GREATEST(sender_id, receiver_id)

上述查询为条目(20, 20, 6)生成一条附加记录。如果要排除具有相同WHEREsender_id的记录,可以在receiver_id子句中添加其他谓词。

答案 1 :(得分:0)

试试这段代码:

SELECT * FROM new_table AS t1
WHERE
(sender_id = 20 OR receiver_id = 20)
AND
(t1.created_time >= 
 (SELECT MAX(created_time) FROM new_table WHERE sender_id = t1.sender_id)
)