我试图只获得两个季节中存在的行。在这两个季节中,产品具有相同的code
例如,在2016赛季,我在products
表中有315个产品,2017年只有28个产品
以下查询提供315 + 28个产品。
SELECT *
FROM products P
INNER JOIN Season S ON S.id = P.id_season
WHERE P.active = 1
AND S.season IN ( 2016, 2017 )
ORDER BY P.code
我需要的是,查询应该只提供2017年的28种产品和2016年的28种产品,其代码与2017年的产品相同。
答案 0 :(得分:3)
看起来像十字路口:
SELECT P.*
FROM products P
INNER JOIN Season S ON S.id = P.id_season
WHERE P.active = 1
AND S.season=2016
INTERSECT
SELECT P.*
FROM products P
INNER JOIN Season S ON S.id = P.id_season
WHERE P.active = 1
AND S.season=2017
ORDER BY P.code
或者,另一个方法。查找2016年的记录,从2017年开始查找并匹配代码:
SELECT * FROM
(
SELECT *
FROM products P
INNER JOIN Season S ON S.id = P.id_season
WHERE P.active = 1
AND S.season=2016
) T1
JOIN
(
SELECT *
FROM products P
INNER JOIN Season S ON S.id = P.id_season
WHERE P.active = 1
AND S.season=2017
) T2 ON T1.Code=T2.Code
ORDER BY T1.Code
答案 1 :(得分:1)
您必须更改并调整:
SELECT *
FROM products P
INNER JOIN Season S ON S.id = P.id_season
WHERE P.active = 1
AND P.id_season IN ( 2016, 2017 )
ORDER BY P.code
答案 2 :(得分:1)
SELECT *
FROM products P
INNER JOIN Season S ON S.id = P.id_season
WHERE P.active = 1
AND S.season IN ( 2017 )
Union All
SELECT *
FROM products
where active = 1
AND Prod_id in (
SELECT Prod_Id FROM products P INNER JOIN Season S ON S.id = P.id_season
WHERE P.active = 1 AND S.season IN ( 2017 )
)
这有用吗?