sql >> Database teknologi >  >> RDS >> Mysql

SQL-forespørgsel til de seneste meddelelser

Da John Woo præciserede, at det ikke er retningsbestemt, er her mit nye svar:

select *
from msgsList
where (least(msg_from, msg_to), greatest(msg_from, msg_to), msg_time)       
in 
(
    select 
       least(msg_from, msg_to) as x, greatest(msg_from, msg_to) as y, 
       max(msg_time) as msg_time
    from msgsList 
    group by x, y
);
 

Output:

| MSG_ID | MSG_FROM | MSG_TO | MSG | MSG_TIME | ------------------------------------------------------------------------ | 1 | 1 | 2 | hello | January, 23 2010 17:00:00-0800 | | 5 | 1 | 3 | me too | January, 23 2012 00:15:00-0800 | | 6 | 3 | 2 | hello | January, 23 2012 01:12:12-0800 |

For dette input:

create table msgsList
(
  msg_id int,
  msg_from int, 
  msg_to int,
  msg varchar(10),
  msg_time datetime
);

insert into msgslist VALUES

(1, 1, 2, 'hello', '2010-01-23 17:00:00'),      -- shown
(2, 2, 1, 'world', '2010-01-23 16:00:00'),

(3, 3, 1, 'i am alive', '2011-01-23 00:00:00'),
(4, 3, 1, 'really', '2011-01-22 23:15:00'),
(5, 1, 3, 'me too', '2012-01-23 00:15:00'),     -- shown

(6, 3, 2, 'hello', '2012-01-23 01:12:12');      -- shown
 

SQLFiddle Demo

Hvis ANSI SQL er din kop te, er det her måden at gøre det på:http://sqlfiddle .com/#!2/0a575/19

select *
from msgsList z
where exists
(
    select null
    from msgsList
    where 
      least(z.msg_from, z.msg_to) = least(msg_from, msg_to)
      and greatest(z.msg_from, z.msg_to) = greatest(msg_from, msg_to)
    group by least(msg_from, msg_to), greatest(msg_from, msg_to)
    having max(msg_time) = z.msg_time  
) ;
 


  1. Sådan afrundes en tid til nærmeste 15-minutters segment

  2. Anonym TABLE- eller VARRAY-type i Oracle

  3. mysql LIKE-forespørgsel tager for lang tid

  4. Sådan udføres et .sql-script fra bash