1

关系型数据库 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,等等。

4

5 回答 5

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

我确信查询中有一些漏洞,但这应该给你一个起点。

编辑:根据问题的最后一部分更正加入。(第一次没看到。)

于 2012-07-18T16:32:40.253 回答
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 更改为您需要匹配的任何 articleID。它应该工作。

于 2012-07-18T16:33:30.920 回答
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
于 2012-07-18T16:36:19.873 回答
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,而是尝试按cnt、sm、mx、mn 顺序按articleid 进行行号分区。这将为您提供数据..

于 2012-07-18T17:05:23.390 回答
0

这是最终起作用的代码:

用 temp as (select a.*, b.articleid as sameAs, 1 as cnt from articletags a left join articletags b on a.tagID=b.tagID where a.articleid=XXX ) select * from Articles where ArticleID in (select sameAs from temp where sameAs<>articleid group by sameAs sum(cnt) = (select count(*) from articletags where articleid=XXX)))

XXX 是传入的 ArticleID。结果是一组与 ArticleID 共享相同文章标签的记录。

于 2012-07-18T23:58:13.390 回答