RDBMS SQL Server,T-SQL
考虑一个链接来自两个不同表格的信息的表:文章和类别。该表包含每个条款的一个或多个条目,其中包含该条目所属的类别的ID。因此,一个
SELECT * FROM TABLE WHERE ARTICLEID = X
返回1到n个结果。
我希望构建一个查询,它允许我比较具有完全相同的类别组合的文章。我一直在尝试使用INTERSECT,但这不会返回任何行。一个例子:
ARTICLEID CATEGORYID
1 1
1 2
1 4
2 1
2 4
3 1
3 2
3 4
4 2
4 4
5 1
5 2
5 4
ARTICLEID = 1
的查询应返回3和5,ARTICLEID = 3
应返回1和5,等等。
答案 0 :(得分:0)
SELECT ART.ID,
ART.COLUMN2,
ART.COLUMN3,
CAT.ID,
CAT.COLUMN2,
CAT.COLUMN3,
ART_CAT.CAT_ID
FROM ARTICLE ART,
CATEGORY CAT,
ARTICLE_CATEGORY ART_CAT
WHERE ART.ID = 1
ART_CAT.CAT_ID = ART.ID
我确信查询中有一些漏洞,但这应该给你一个起点。
编辑:根据问题的最后部分更正了加入次数。 (第一次没看到它。)
答案 1 :(得分:0)
编辑:这应该有效
with temp as
(
select a.*, b.articleid as bart, 1 as cnt from tableName a left join
tableName b on a.CATEGORYID=b.CATEGORYID where a.articleid=XXX
)
select bart from temp where bart<>articleid group by bart having sum(cnt) =
(select count(*) from tableName where articleid=XXX)
只需运行此确切查询,仅将XXX更改为您需要匹配的任何文章ID。它应该工作。
答案 2 :(得分:0)
你试过Right Join
吗?
create table category
(
Categoryid int
)
insert into category(Categoryid)values(1)
insert into category(Categoryid)values(2)
insert into category(Categoryid)values(3)
insert into category(Categoryid)values(4)
insert into category(Categoryid)values(5)
create table articles
(
Articleid int,
Categoryid int
)
insert into articles(Articleid, Categoryid)values(1, 1)
insert into articles(Articleid, Categoryid)values(1, 2)
insert into articles(Articleid, Categoryid)values(1, 4)
insert into articles(Articleid, Categoryid)values(2, 1)
insert into articles(Articleid, Categoryid)values(2, 4)
Select c.Categoryid
From
(
Select * from articles where Articleid = 2
)a
right Join category c on c.Categoryid = a.Categoryid
drop table articles
drop table category
答案 3 :(得分:0)
试试这个。如果一切都是整数。
with mycte as
(
select articleid,count(*) as cnt,sum(categoryid) as sm,max(categoryid) mx,min(categoryid) mn
from mytable
group by articleid
)
select mc.articleid,mc1.articleid from mycte mc inner join mycte mc1 on mc.sm = mc1.sm
and mc.mn = mc1.mn
and mc.mx = mc1.mx
and mc.cnt = mc1.cnt
and mc.articleid <> mc1.articleid
如果你需要在一行中,那么你不需要加入cte,而是通过cid,sm,mx,mn按照articleid来尝试行号分区。这将为你提供数据..
答案 4 :(得分:0)
这是最终有效的代码:
使用temp as(选择一个。*,b.articleid作为sameAs,1作为cnt来自articletags左边的连接articletags b on a.tagID = b.tagID,其中a.articleid = XXX)select from from Articles where in ArticleID in (从temp中选择sameAs,其中sameAs&lt;&gt; articleid group by sameAs has sum(cnt)=(select article(*)from articletags where articleid = XXX)))
XXX是传入的ArticleID。结果是一组记录与ArticleID共享相同的文章标签。