获取用户id w.r.t到发送者的行数

时间:2014-01-20 13:53:38

标签: mysql sql

我构建了一个私人消息系统:

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)
);





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-2,2-1是相同的计数,1-1是相同的计数,1-3,3-1是相同的计数和{ {1}}是相同的计数。基本计算用户发件人,发件人用户之间的所有互动。

所需的输出(如果我是用户1)

2-3,3-2

我非常感谢任何帮助。谢谢你。

2 个答案:

答案 0 :(得分:1)

原来的答案消失了,请允许我再发一次:

SELECT
 LEAST(sender, receiver) as X,
 GREATEST(sender, receiver) as Y,
 COUNT(1)
FROM
 tblA
GROUP BY
 X, Y;

这将选择两个人之间的每一组互动。根据您的要求,您将无法告诉谁联系了谁。你只能告诉两个人之间有多少次互动。

昨天我做了here's the fiddle

答案 1 :(得分:0)

这我认为工作和输出你问的。我不是平方组的粉丝,因为例如23 * 23 + 89 * 89 = 8450 = 13 * 13 + 91 * 91(但我可能错过了一些东西)

select one, two, if(one=two,sum(cnt)/2,sum(cnt)) AS NUMBER from
(
select sender as one,receiver as two, count(*) as cnt from tblA group by sender, receiver
union all
select receiver as one ,sender as two, count(*) as cnt from tblA group by sender, receiver
) a
group by one, two
order by one, two

http://sqlfiddle.com/#!2/9d150/15