数据库:SQL Server 2008
如果该用户ID在两个表中多次出现,我想从表中选择id, title
和userid
。
因此,如果用户在位置表中有2条记录,在艺术家表中有1条记录,那么我想返回所有3条记录的id,title和userid。
这就是我现在所拥有的,但它会返回0条记录。
当我省略“有计数(用户ID)> 1”部分时,我会在所有表格中获得所有400条记录。
select userid,id,title from (
select id,title,userid from locations l
union
select id,title,userid from artists a
) as info
group by userid,id,title
having count(userid)>1
答案 0 :(得分:1)
这样的事情应该有效:
select userid,id,title
from
( select id,title,userid from locations l union select id,title,userid from artists a )
as grabfromthis
where userid in (
select userid
( select id,title,userid from locations l union select id,title,userid from artists a )
as info
group by userid having count(userid)>1)
答案 1 :(得分:1)
我稍微修改了上面的内容,使其更加光滑:
WITH combined AS
(
SELECT id from t1
UNION ALL
SELECT id FROM t2
etc...
)
SELECT id, count(id) as numOccurrences
FROM combined
GROUP BY id
HAVING count(id) > 1
不同之处在于,这将显示您的号码重复次数。
你也可以添加
ORDER BY numOccurrences to chop down your worst offenders first
答案 2 :(得分:0)
;WITH combined AS (
SELECT id, title, userid FROM locations
UNION ALL
SELECT id, title, userid FROM artists
)
SELECT *
FROM combined c
INNER JOIN (
SELECT userid
FROM combined
GROUP BY userid
HAVING COUNT(*) > 1
) g ON c.userid = g.userid
从UNION子查询中获取非唯一userid
列表,并将其连接回userid
上的子查询。子查询仅作为CTE实现一次。