[英]If logic in SQL or Access queries
問候,SO人。
我正在開發一個讓我使用Access數據庫的項目。 這是設置:
我有三張桌子:
Tab1 with employee names, ID#s, Manager names and Manager ID#s.
Tab2 with chat info, employee ID#s and employee names.
Tab3 with Manager ID#s, Manager names and team names.
我目前有一個選擇以下內容的查詢:
tab2.[employee name], tab2.[employee id], tab3.[chat info], tab1.[manager id], tab1.[manager id], tab3.[team name]
where
tab2.[employee id] = tab1.[employee id] and tab2.[manager id] = tab3.[manager id];
我想要完成的是:如果ID在行的某個地方不匹配,我想有辦法在“團隊”字段中放置“未知”。 有任何想法嗎?
提前致謝!
也許是這樣的:
select tab2.[employee name],
tab2.[employee id],
tab3.[chat info],
tab1.[manager id],
Nz(tab3.[team name], 'Unknown') as [team name]
from (tab2
left join tab1
on tab2.[employee id] = tab1.[employee id])
left join tab3
on tab2.[manager id] = tab3.[manager id]
SELECT
tab2.[employee name], tab2.[employee id],
tab3.[chat info], tab1.[manager id],
tab1.[manager id],
Nz(tab3.[team name],"Unknown")
FROM (tab2
LEFT JOIN tab1
ON tab2.[employee id] = tab1.[employee id])
LEFT JOIN tab3
ON tab2.[manager id] = tab3.[manager id];
似乎Access不支持SQL case語句,所以我以前的答案是不正確的。 我將它留給那里尋找與SQL兼容的數據庫相同問題的人。
顯然你可以使用switch語句來實現相同的結果; 此示例顯示了如何使用交換機 。 希望這更有幫助。
否則,如果可能,切換到真正的DB :)
好吧,由於你不能使用CASE,我的速度很慢,而Joe使用Nz可能是你最好的選擇,但是還有另一種特定於Access的替代方案,以防萬一更適合你的情況:
select tab2.[employee name],
tab2.[employee id],
tab3.[chat info],
tab1.[manager id],
Iif(IsNull(tab3.[team name]), 'Unknown', tab3.[team name]) as [team name]
from tab2
left join tab1
on tab2.[employee id] = tab1.[employee id]
left join tab3
on tab2.[manager id] = tab3.[manager id]
在這種情況下,Iif ( condition,trueAnswer,falseAnswer )與Nz做同樣的事情,但是如果你的條件不是IsNull,它可以更靈活。
我不確定Access,但在SQL中通常你會加入你的表,你可以使用CASE語句來添加你想要的條件行為; 訪問可能不支持這一點。
此處顯示的示例相當標准。
哇,訪問查詢真的是這樣的嗎? 嗯......那么也許是這樣的。
tab2.[employee name], tab2.[employee id], tab3.[chat info], tab1.[manager id], tab1.[manager id], case when tab3.[team name] is null then 'Unknown' else tab3.[team name] end as [team name]
where
tab2.[employee id] = tab1.[employee id] and tab2.[manager id] = tab3.[manager id];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.