0

我正在通过执行一些多个联接来获取记录。我需要在 OR 条件下再添加一个。

有一张桌子Payment。从Payment必须加入:

  • 表 Package1(如果 Payment.PaymentTypeID=1)或
  • 表 Package2(如果 Payment.PaymentTypeID=3)。

表 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
4

4 回答 4

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在连接条件中通常会使优化查询变得更加困难。

编辑:

如果您有两个表,那么 aleft 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;
于 2013-09-19T11:32:17.097 回答
1

尝试 :

select 
   P1.VoucherID 
from 
   Payment P 
inner join Package1 P1 
   on P1.empid=P.empid 
   and P.PaymentTypeID IN (1,3)
于 2013-09-19T11:32:15.277 回答
0

I would do them in 1 select statment and then use COALESCE to extract the first non-null value.

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
于 2013-09-19T11:50:45.323 回答
0

我将从表 Package1 和 2 中检索凭证,然后使用 IF() 函数根据 PaymentTypeId 的值决定选择什么。

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;
于 2013-09-19T11:39:56.943 回答