[英]Where/ And Clause in Join Statement to avoid duplicates
我是SQL的新手-我已經仔細閱讀了這些帖子,但無法完全解決我的問題的答案。 我正在嘗試在join子句中使用where /或語句來做我認為應該是一個簡單查詢的事情。
問題是我似乎正在重復。 這是我正在使用的代碼:
select A.[AuctionId], AA.attribute_id
from [auction] A
left join [auction_attribute] AA
on AA.auction_id = A.AuctionId
where AA.attribute_id = 127
or (AA.attribute_id = 132 and AA.text_data = 'USABLE')
我想獲取屬性ID為127的所有記錄,並且記錄的屬性132還需要具有關聯的text_data'USABLE',如果這有意義的話? 一條記錄可以有多個屬性ID,因此我想獲得所有127個與它們的132關聯的text_data也是“ USABLE”的位置。 我本來是用子查詢來完成查詢的,但是我認為這將是一種更有效的方法,如果我能正確解決的話!
上面的代碼當前返回重復的記錄,如果我將“或”替換為“和”,則不會獲得任何記錄。 誰能幫忙嗎?
編輯:按照Turophile的建議,用簡單的內部聯接替換左外部聯接(謝謝)
您的實際查詢意思是:
獲取所有屬性值為127的記錄,以及所有屬性值為132的與USABLE相關聯的記錄。
如果確實需要它,但沒有重復,則查詢可能像這樣:
select distinct A.[AuctionId], AA.attribute_id
from [auction] A
join [auction_attribute] AA
on AA.auction_id = A.AuctionId
where AA.attribute_id = 127
or (AA.attribute_id = 132 and AA.text_data = 'USABLE')
您的描述似乎是:
獲取具有127 AND屬性和132與USABLE相關聯的屬性的記錄
如果是您想要的,查詢應該是:
select A.[AuctionId], AA.attribute_id, AA2.attribute_id
from [auction] A
join [auction_attribute] AA
on AA.auction_id = A.AuctionId
join [auction_attribute] AA2
on AA2.auction_id = A.AuctionId
where AA.attribute_id = 127
and (AA2.attribute_id = 132 and AA2.text_data = 'USABLE')
如果是SQL,則可以使用同一張表多次,但要為其提供不同的別名。
編輯:根據Turophile的建議,我在查詢中使用了簡單的內部聯接。 僅當您要從一個表中獲取記錄時才需要使用外部聯接,即使另一個表不包含它們也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.