在同一张表中查找相似的记录

时间:2019-11-29 09:47:10

标签: sql sql-server in-clause

我正在同一张表中寻找类似的记录。我尝试了IN子句(在查询下方),但未按预期运行。

Select * from tblBlogCategory Where CategoryID IN (Select CategoryID from tblBlogCategory Where BlogID=1)

即我有BlogID=1。我想要类别ID为1和2的表中的那些记录。如果有任何新的CategoryID 3,也可以。因此,对于下表,它应返回BlogID 3。

我该如何实现?

enter image description here

预期输出:
enter image description here

3 个答案:

答案 0 :(得分:1)

尝试一下:

表架构:

CREATE TABLE YourTable(BlogId INT, CategoryId INT)

INSERT INTO YourTable VALUES(1,1)
INSERT INTO YourTable VALUES(1,2)
INSERT INTO YourTable VALUES(2,1)
INSERT INTO YourTable VALUES(3,1)
INSERT INTO YourTable VALUES(3,2)
INSERT INTO YourTable VALUES(3,3)

查询:

DECLARE @BlogID INT = 1

SELECT * 
FROM YourTable  
WHERE BlogID IN(
    SELECT A.BlogID 
    FROM YourTable A
    JOIN (
        SELECT CategoryId
        FROM YourTable
        WHERE BlogID = @BlogID
    )B ON A.CategoryId = B.CategoryId
    GROUP BY A.BlogID
    HAVING COUNT(DISTINCT A.CategoryId)>=(SELECT COUNT(DISTINCT CategoryId) FROM YourTable WHERE BlogID = @BlogID)
  )
AND BlogID != @BlogID

输出:

| BlogId | CategoryId |
|--------|------------|
|      3 |          1 |
|      3 |          2 |
|      3 |          3 |

SQL Fiddle Link

答案 1 :(得分:0)

如果我正确理解了您,您可以使用

select * from tblBlogCategory where BlogID=1

您应该在BlogID = 1处获得所有CategoryID,也可以对其进行进一步过滤

 select * from tblBlogCategory where BlogID=1 and CategoryID in (1,2)

答案 2 :(得分:0)

如果您只想返回具有匹配项的博客ID,那么就足够了:

select bc.blogid
from tblBlogCategory bc join
     tblBlogCategory bc1
     on bc1.categoryid = bc.categoryid and
        bc1.blogid = 1 and
        bc1.blogid <> bc.blogid
group by bc.blogid
having count(*) = (select count(*) from tblBlogCategory bc where bc.blogid = 1);