我通过做一些多个连接来获取记录。我需要添加一个OR条件。
有一张表Payment
。来自Payment
必须加入:
表Package1和Package2都有一个列VoucherID,必须根据上述条件获取。我可以通过下面的查询使用Union或Union All来做到这一点,但是如果我不使用UNion或Union All就可以告诉我。
select P1.VoucherID from Payment P
inner join Package1 P1 on P1.empid=P.empid and P.PaymentTypeID=1
union all
select P2.VoucherID from Payment P
inner join Package1 P2 on P2.empid=P.empid and P.PaymentTypeID=3
答案 0 :(得分:2)
您可以将or
置于on
条件:
select P1.VoucherID
from Payment P inner join
Package1 P1
on (P1.empid=P.empid and P.PaymentTypeID=1) or
(P1.empid=P.empid and P.PaymentTypeID=3);
反过来,这可以写成:
select P1.VoucherID
from Payment P inner join
Package1 P1
on (P1.empid=P.empid and P.PaymentTypeID in (1, 3);
union
版本很可能会表现得更好。连接条件中的or
通常会使查询更加困难。
编辑:
如果您有两个表,那么left outer join
可能有效:
select coalesce(P1.VoucherID, P2.VoucherId) as VoucherId
from Payment P left outer join
Package1 P1
on (P1.empid = P1.empid and P.PaymentTypeID=1) left outer join
Package2 P2
on (P1.empid = P2.empid and P.PaymentTypeID=3)
where P1.VoucherId is not null or P2.VoucherId is not null;
答案 1 :(得分:1)
尝试:
select
P1.VoucherID
from
Payment P
inner join Package1 P1
on P1.empid=P.empid
and P.PaymentTypeID IN (1,3)
答案 2 :(得分:0)
我从两个表Package1和2中检索凭证,然后根据PaymentTypeId的值使用IF()函数决定选择什么。
select IF(P.PaymentTypeID=1, P1.VoucherID, P2.VoucherID) as VoucherId from Payment P
inner join Package2 P2 on P2.empid=P.empid
inner join Package1 P1 on P1.empid=P.empid;
答案 3 :(得分:0)
我会在1个select语句中执行它们,然后使用COALESCE
来提取第一个非null值。
SELECT
COALESCE(P1.VoucherID, P2.VoucherID) as VoucherID
FROM
Payment P
INNER JOIN
Package1 P1
ON
P1.empid = P.empid AND P.PaymentTypeID = 1
INNER JOIN
Package2 P2
ON
P2.empid = P.empid AND P.PaymentTypeID = 3