【发布时间】:2009-06-12 21:23:01
【问题描述】:
这一定是一个简单的问题,现在只是愚蠢的......
我有一张桌子,叫做“foo”。它有两列,“id”和“username”。
id 是唯一的,但有些用户名引用的是同一个用户;只有一个在“xx_”的用户名上有前缀。
ex:
ID USERNAME
1 bob
2 sam
3 xx_bob
如何确定哪些用户的对应对象具有“xx_”前缀?那么哪些没有呢?
【问题讨论】:
这一定是一个简单的问题,现在只是愚蠢的......
我有一张桌子,叫做“foo”。它有两列,“id”和“username”。
id 是唯一的,但有些用户名引用的是同一个用户;只有一个在“xx_”的用户名上有前缀。
ex:
ID USERNAME
1 bob
2 sam
3 xx_bob
如何确定哪些用户的对应对象具有“xx_”前缀?那么哪些没有呢?
【问题讨论】:
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 中应该类似
【讨论】:
这将为您提供两行的 ID:
select * from foo a1 join foo a2 on (a2.username=concat('xx_',a1.username));
【讨论】:
如果您想要每行不重复,请使用 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_%'
【讨论】: