按接收者名称以外的其他用户名分组

时间:2014-01-25 15:26:36

标签: mysql sql

我有以下"tblA""tblB"表:

CREATE TABLE if not exists tblA
(
  id int(11) NOT NULL auto_increment,
  sender varchar(255),
  receiver varchar(255),
  msg varchar(255),
  date timestamp,
  PRIMARY KEY (id)
);

CREATE TABLE if not exists tblB
(
  id int(11) NOT NULL auto_increment,
  sno varchar(255),
  name varchar(255),
  PRIMARY KEY (id)
);

INSERT INTO tblA (sender, receiver, msg,date) VALUES
('1', '2', 'buzz ...','2011-08-21 14:11:09'),
('1', '2', 'test ...','2011-08-21 14:12:19'),
('1', '2', 'check ...','2011-08-21 14:13:29'),
('1', '1', 'test2 ...','2011-08-21 14:14:09'),
('2', '1', 'check2 ...','2011-08-21 14:15:09'),
('2', '1', 'test3 ...','2011-08-21 14:16:09'),
('1', '2', 'buzz ...','2011-08-21 14:17:09'),
('1', '2', 'test ...','2011-08-21 14:18:19'),
('1', '2', 'check ...','2011-08-21 14:19:29'),
('1', '1', 'test2 ...','2011-08-21 14:10:09'),
('3', '1', 'check2 ...','2011-08-21 14:21:09'),
('3', '1', 'test3 ...','2011-08-21 14:22:09'),
('3', '2', 'buzz ...','2011-08-21 14:24:09'),
('3', '2', 'test ...','2011-08-21 14:25:19'),
('1', '3', 'check ...','2011-08-21 14:26:29'),
('1', '3', 'test2 ...','2011-08-21 14:27:09'),
('2', '3', 'check2 ...','2011-08-21 14:28:09'),
('2', '3', 'test3 ...','2011-08-21 14:29:09'),
('1', '2', 'check3 ...','2011-08-21 14:23:09'),
('1', '4', 'test2 ...','2011-08-21 14:27:09'),
('1', '5', 'test2 ...','2011-08-21 14:27:09'),
('2', '6', 'check2 ...','2011-08-21 14:28:09'),
('2', '7', 'test3 ...','2011-08-21 14:29:09'),
('8', '2', 'check3 ...','2011-08-21 14:23:09');


INSERT INTO tblB (sno, name) VALUES
('1', 'Aa'),
('2', 'Bb'),
('3', 'Cc'),
('4', 'Dd'),
('5', 'Ee'),
('6', 'Ff'),
('7', 'Gg'),
('8', 'Hh');

我希望人员列表Aa正在按日期排序(每个用户组的最后一个条目)。

Bb
Cc
Dd
Ee
Ff
Gg
Hh

我不知道如何在不查询"Aa"的情况下对其进行分组。

1 个答案:

答案 0 :(得分:2)

如果我理解正确:

select b.name
from tblA a join
     tblB b
     on b.id in (a.receiver, a.sender)
where b.name <> 'Aa'
order by date desc;

Here是一个SQL小提琴。请注意,上面的代码有一些分号,应该是逗号。

编辑:

如果您想要最近的日期,请使用:

select b.name
from tblA a join
     tblB b
     on b.id in (a.receiver, a.sender)
where b.name <> 'Aa'
group by b.name
order by max(date) desc;

编辑II:

按照只有'Aa'的行进行过滤:

select b.name
from tblA a join
     tblB b
     on b.id in (a.receiver, a.sender)
where b.name <> 'Aa' and
      exists (select 1
              from tblB b2
              where b2.name = 'Aa' and
                    b2.id in (a.receiver, a.sender)
             )
group by b.name
order by max(date) desc;