[英]select query with many-on-many table
我有一张桌子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'
如何在一个结果列中组合这两个查询?
你可以用3种方法做到这一点。
方法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'
UNION ALL
。 如果您不希望允许重复,请使用UNION
。 =
运算符而不是LIKE
,因为您没有进行任何模式匹配。 你可以试试这个
select BarcodeAlternatief AS 'Barcode' from dbo.ArtikelAlternatief where Barcode like '7630015711115'
Union All
select Barcode AS 'Barcode' from dbo.ArtikelAlternatief where BarcodeAlternatief like '7630015711115'
放'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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.