需要多个where子句或更好的条件语句方式

时间:2016-03-07 22:45:29

标签: sql tsql conditional

我正在试图弄清楚如何根据另一个表中是否存在值来在一个表中显示数据。我已经研究了案例陈述,但无法弄清楚它在我目前的情况下会如何应用。

我有两个表CompanyRequestOffTakeOver,我希望能够从CompanyRequestOff中选择TransactionID s等于User的列。列不能相同。

任何帮助甚至指向正确的方向都会有用,谢谢。

CompanyRequestOff表包含以下列:

TransactionID
Requestee
RequestedDate
RequestedTimeSlot
RequestedPosition
RequestStatus
LastUpdate
Manager         

TakeOver表格包含:

Id
TransactionID
RequestedUser
RequestStatus
LastUpdate
Manager

这是我尝试解决这个问题:

SELECT
    CompanyRequestOff.TransactionID, CompanyRequestOff.Requestee,
    CompanyRequestOff.RequestedDate, CompanyRequestOff.RequestedTimeSlot,
    CompanyRequestOff.RequestedTimeSlot, CompanyRequestOff.RequestedPosition,
    CompanyRequestOff.RequestStatus, CompanyRequestOff.LastUpdate, 
    CompanyRequestOff.Manager 
FROM
    CompanyRequestOff, TakeOver 
WHERE
    RequestedDate > GETDATE() 
    AND CompanyRequestOff.RequestStatus = 'Requested' 
    AND CompanyRequestOff.TransactionID = TakeOver.TransactionID  
    AND TakeOver.RequestedUser != @UserN;

唯一相关的列是transactionID列,它在CompanyRequestOff中是主要的,在TakeOver中是外来的。我想显示CompanyRequestOff表中TakeOver中没有行的列transactionID但是只有当它包含某个TakeOver.RequestedUser值时才会显示。< / p>

2 个答案:

答案 0 :(得分:2)

听起来你想在两个条件下join这两个表:

SELECT *
FROM CompanyRequestOff CRO
JOIN TakeOver TO on TO.TransactionID = CRO.TransactionID and TO.User <> CRO.User

更新以解释您的修改帐号:

  

我想显示CompanyRequestOff中的列   table其中,在具有该transactionID的TakeOver中没有行但是   只有它包含某个TakeOver.RequestedUser值。

您可以使用where transactionID not in子句实现transactionID部分:

SELECT *
FROM CompanyRequestOff
WHERE TransactionID not in 
     (SELECT TransactionID FROM TakeOver)

然后添加用户部分:

SELECT *
FROM CompanyRequestOff
WHERE TransactionID not in 
    (SELECT TransactionID FROM TakeOver WHERE RequestedUser <> @UserN)

使用您查询中的所有逻辑:

SELECT *
FROM CompanyRequestOff
WHERE TransactionID not in 
    (SELECT TransactionID FROM TakeOver WHERE RequestedUser <> @UserN)
AND RequestedDate > GETDATE()
AND RequestStatus = 'Requested'

答案 1 :(得分:0)

查看您的问题,您似乎在CompanyRequestOffTakeOver - UserTransactionID之间有两个常见列。因此,您的查询应该是这样的,您可以从CompanyRequestOff中选择TransactionID匹配的所有记录,但user不匹配。

select c.* from CompanyRequestOff c, TakeOver t
where c.TransactionId = t.TransactionId 
and c.user != t.user