【问题标题】:compare values of same column on same table比较同一表上同一列的值
【发布时间】:2009-06-12 21:23:01
【问题描述】:

这一定是一个简单的问题,现在只是愚蠢的......

我有一张桌子,叫做“foo”。它有两列,“id”和“username”。

id 是唯一的,但有些用户名引用的是同一个用户;只有一个在“xx_”的用户名上有前缀。

ex:
ID      USERNAME
1       bob
2       sam
3       xx_bob

如何确定哪些用户的对应对象具有“xx_”前缀?那么哪些没有呢?

【问题讨论】:

    标签: mysql select


    【解决方案1】:
    select * from foo where username 
     IN (select replace(username, 'xx_', '') from foo where username like 'xx_%')
    

    它的作用是将整个表与 IN 动词后的子查询生成的子列表进行比较。

    相反,您可以简单地使用 NOT IN 代替 IN。

    注意:这是一个 t-sql (MS SQL 2005) 查询,在 MySQL 中应该类似

    【讨论】:

      【解决方案2】:

      这将为您提供两行的 ID:

      select * from foo a1 join foo a2 on (a2.username=concat('xx_',a1.username));
      

      【讨论】:

        【解决方案3】:

        如果您想要每行不重复,请使用 duplicate_id:

        SELECT foo.*, f2.id AS duplicate_id FORM foo
        LEFT OUTER JOIN foo AS f2 ON ( f2.username = concat( 'xx_', foo.username ) )
        WHERE foo.id NOT LIKE 'xx_%'
        

        【讨论】:

          猜你喜欢
          • 2014-03-23
          • 2017-02-14
          • 2018-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多