选择具有多对多表的查询

时间:2014-08-22 10:08:26

标签: sql select

我有一张桌子dbo.ArtikelAlternatief像这样创建:

CREATE TABLE [dbo].[ArtikelAlternatief]( 
    [Barcode] [varchar](50) NOT NULL,
    [BarcodeAlternatief] [varchar](50) NOT NULL,   
 CONSTRAINT [PK_ArtikelAlternatief] PRIMARY KEY CLUSTERED 
(
    [Barcode] ASC,
    [BarcodeAlternatief] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

现在我想要结合以下结果:

select BarcodeAlternatief AS 'Barcode' from dbo.ArtikelAlternatief where Barcode like '7630015711115' 
select Barcode AS 'Barcode' from dbo.ArtikelAlternatief where BarcodeAlternatief like '7630015711115'

如何将这两个查询组合在一个结果列中?

4 个答案:

答案 0 :(得分:2)

使用UNION运算符:

query1
UNION ALL
query2

ALL关键字是可选的,如果您想要重复的行,则使用它。

答案 1 :(得分:2)

你可以用3种方法做到。

SQLFIDDLE

方法1: 使用CASE声明:

select 
     (case when Barcode = '7630015711115' 
            then BarcodeAlternatief
            else Barcode END) as 'Barcode'  
    from ArtikelAlternatief
    where Barcode = '7630015711115'
          or BarcodeAlternatief = '7630015711115';

方法2: 您可以尝试使用DECODE语句(Of oracle),

SELECT  DECODE (BarcodeAlternatief , '7630015711115', Barcode , BarcodeAlternatief ) AS Barcode 
FROM dbo.ArtikelAlternatief 
where Barcode = '7630015711115' OR BarcodeAlternatief = '7630015711115'

方法3:

使用UNION ALL尝试以下查询:

select BarcodeAlternatief AS 'Barcode' from dbo.ArtikelAlternatief 
where Barcode = '7630015711115' 

UNION ALL

select Barcode AS 'Barcode' from dbo.ArtikelAlternatief 
where BarcodeAlternatief = '7630015711115'
  1. 如果您希望允许重复,请使用UNION ALL。如果您不希望允许重复,请使用UNION
  2. 在您的情况下,您可以在where条件中使用=运算符而不是LIKE,因为您没有进行任何模式匹配。

答案 2 :(得分:1)

你可以试试这个

select BarcodeAlternatief AS 'Barcode' from dbo.ArtikelAlternatief where Barcode like '7630015711115' 

Union All

select Barcode AS 'Barcode' from dbo.ArtikelAlternatief where BarcodeAlternatief like '7630015711115'

答案 3 :(得分:1)

Put' OR'和' CASE'功能条件:

select 
     (case when Barcode like '7630015711115' then BarcodeAlternatief
           when BarcodeAlternatief like '7630015711115' the Barcode 
            else '') as 'Barcode'  
    from dbo.ArtikelAlternatief
    where Barcode like '7630015711115'
          or BarcodeAlternatief like '7630015711115'