我正在运行MSSQL Server 2016 Express。我想选择具有特定articlegroup_id
值的所有行,并选择具有匹配articleid
值的行。
因此,使用下面的数据,假设我想获得值为684的articlegroup_id
的结果集。
只有articleid的3107196和3100000匹配。所以结果集将是:
3100000 129
3100000 144
3100000 684
3107196 129
3107196 144
3107196 684
同样,如果我在articlegroup_id
上运行相同的查询,其值为112,我想得到:
2106543 110
2106543 112
2106999 110
2106999 112
DDL
CREATE TABLE [dbo].[products_category_mapping](
[articleid] [int] NOT NULL,
[articlegroup_id] [int] NOT NULL
) ON [PRIMARY]
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (3100000,129)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (3100000,144)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (3100000,684)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (3107196,129)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (3107196,144)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (3107196,684)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (3107100,129)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (3107100,144)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (2106543,110)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (2106543,112)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (2107000,110)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (2106999,110)
INSERT INTO products_category_mapping(articleid,articlegroup_id) VALUES (2106999,112)
答案 0 :(得分:3)
另一种方法是使用JOIN
Select A.*
From [products_category_mapping] A
Join (
Select articleid from [products_category_mapping] where articlegroup_id=684
) B on A.articleid=B.articleid
答案 1 :(得分:2)
您可以使用子查询查找给定articlegroupid的articleids,然后获取具有匹配的articleids的所有行
select *
from products_category_mapping
where articleid in (
select articleid
from products_category_mapping
where articlegroup_id = 684
)
另一种方法是使用join:
select p1.*
from products_category_mapping p1
inner join products_category_mapping p2
on p1.articleid = p2.articleid
and p2.articlegroup_id = 684;
答案 2 :(得分:2)
这是一种方法:
DECLARE @articlegroup_id int = 112
;WITH CTE
AS
(
SELECT articleid
FROM products_category_mapping
WHERE articlegroup_id = @articlegroup_id
)
SELECT articleid, articlegroup_id
FROM products_category_mapping main
WHERE EXISTS (
SELECT 1
FROM CTE
WHERE CTE.articleid = main.articleid
)
结果:
articleid articlegroup_id
2106543 110
2106543 112
2106999 110
2106999 112
答案 3 :(得分:2)
首先,没有名为SQL Server 2015
关于解决方案,请在where
子句中使用子查询,如下所示: -
select * from [products_category_mapping]
where articleid in (
select articleid
from [products_category_mapping] where articlegroup_id = 684)
<强>结果: - 强>
答案 4 :(得分:1)
你可以使用exists来做这些:
select * products_category_mapping products1
where exists (select null from products_category_mapping products2
where products1.articleid = products2.articleid
and products2.articlegroup_id = 684);