在相同 table 中查找相似记录
Find similar records in the same table
我正在寻找相同 table 中的相似记录。我尝试了 IN
子句(在查询下方),但它没有按预期工作。
Select * from tblBlogCategory Where CategoryID IN (Select CategoryID from tblBlogCategory Where BlogID=1)
即我有 BlogID=1
。我想要 table 中 CategoryID 分别为 1 和 2 的那些记录。如果有任何新的 CategoryID 3 也很好。所以,对于下面的table,它应该return BlogID 3。
我如何实现这一目标?
预期输出:
试试这个:
Table 架构:
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 |
如果我猜对了,你可以使用
select * from tblBlogCategory where BlogID=1
你应该得到所有 CategoryID where BlogID=1 你也可以进一步过滤
select * from tblBlogCategory where BlogID=1 and CategoryID in (1,2)
如果您只想 return 具有匹配项的博客 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);
我正在寻找相同 table 中的相似记录。我尝试了 IN
子句(在查询下方),但它没有按预期工作。
Select * from tblBlogCategory Where CategoryID IN (Select CategoryID from tblBlogCategory Where BlogID=1)
即我有 BlogID=1
。我想要 table 中 CategoryID 分别为 1 和 2 的那些记录。如果有任何新的 CategoryID 3 也很好。所以,对于下面的table,它应该return BlogID 3。
我如何实现这一目标?
预期输出:
试试这个:
Table 架构:
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 |
如果我猜对了,你可以使用
select * from tblBlogCategory where BlogID=1
你应该得到所有 CategoryID where BlogID=1 你也可以进一步过滤
select * from tblBlogCategory where BlogID=1 and CategoryID in (1,2)
如果您只想 return 具有匹配项的博客 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);