【问题标题】:Query to find users who share same account number查询查找共享相同账号的用户
【发布时间】:2013-07-22 18:20:25
【问题描述】:

我目前正在学习mysql。我能够创建一个名为 user 的表(如下所示)。每个用户都有一个唯一的 id。一些用户共享相同的帐号。我没有运气编写一个查询来显示共享相同帐号的用户的结果。我该怎么办?

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account` int(11) NOT NULL,
  `role` enum('default','admin','owner') NOT NULL DEFAULT 'default',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 

【问题讨论】:

    标签: mysql


    【解决方案1】:
    select id, a.account from users u,
    (select account from users
    group by account
    having count(*)>1) a
    where u.account=a.account
    order by u.account
    

    【讨论】:

      【解决方案2】:

      试试这个

       SELECT * FROM `user`
       WHERE account IN (SELECT account FROM user GROUP BY account HAVING COUNT(*)>1)
      

      【讨论】:

        【解决方案3】:
        select a.id, b.id 
        from users as a, users as b
        where a.account=b.account and a.id < b.id;
        

        这会找到共享一个帐户的用户对。

        这有一些缺点:

        1. 每当 M 人共享一个帐户时,就有 M*(M-1)/2 个这样的对。
        2. 它做了一个表自连接,所以时间 ~ O(N^2)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-19
          相关资源
          最近更新 更多