在SQL Server 2016中,我有一个包含两个varchar
列的表,其中包含要比较的事物的名称(比如SUBJECT和COMP)。由于比较值是相同的,无论A-> B还是B-> A,所以存储两者都没有意义,所以我只存储A-> B。这在SELECT
上提出了一个新问题。基本上是:
CREATE TABLE myTable(Subject varchar(50), Comp varchar(50))
INSERT INTO myTable(Subject, Comp) values ('SDSD', 'CFGT')
INSERT INTO myTable(Subject, Comp) values ('FMIP', 'ABLQ')
INSERT INTO myTable(Subject, Comp) values ('FMIP', 'FMIP')
DECLARE @sub varchar(50), @comp varchar(50)
SET @sub = 'ABLQ', @comp = 'FMIP;
我似乎无法弄清楚如何说“给我一行,其中'ABLQ'和'FMIP'的组合可以存在于任一列中,但这两列必须包含两个值(换句话说, 'ABLQ'/'ABLQ'和'FMIP'/'FMIP'将不会返回,但是'ABLQ'/'FMIP'和'FMIP'/'ABLQ'都会 - 或者我应该说两者都会,但因为只有一个实际上存在两个。我已经尝试了几种组合,似乎无法在逻辑部门得到正确的结果。我最终得到类似的东西
SELECT *
FROM myTable
WHERE (Subject = @sub OR Comp = @sub)
AND (Subject = @comp OR Comp = @Comp)
AND (Subject <> @sub AND Comp <> @comp)
有什么想法吗?
答案 0 :(得分:1)
在拥有正确值的行后,确保两列不相等:
SELECT * FROM myTable
WHERE
(Subject=@sub OR Subject=@comp) AND
(Comp=@sub OR Comp=@comp) AND
(Subject <> Comp)
答案 1 :(得分:0)
我倾向于把逻辑写成:
SELECT t.*
FROM myTable t
WHERE (Subject = @sub AND Comp = @comp) OR
(Subject = @comp AND Comp = @sub) ;
我觉得这个配方更容易理解。