經過一個實例簡述數據庫查詢裏FIND_IN_SET() 和IN()區別html
問題: mysql
數據庫中有兩個表: Orders 和 Companiessql
Orders的表結構: 數據庫
OrderID | attachedCompanyIDs ------------------------------------ 1 1,2,3 2 2,4
Campany表結構:數組
CompanyID | name -------------------------------------- 1 Company 1 2 Another Company 3 StackOverflow 4 Nothing
樓主給出兩種查詢方式:spa
第一種:code
SELECT name FROM orders,company WHERE orderID = 1 AND FIND_IN_SET(companyID, attachedCompanyIDs)工做正常. 查詢結果以下:
name --------------- Company 1 Another Company StackOverflow
第二種:htm
SELECT name FROM orders,company WHERE orderID = 1 AND companyID IN (attachedCompanyIDs)出現問題, 查詢結果以下:
name --------------- Company 1 Another Company StackOverflow
做何解釋?字符串
答案:get
使用關鍵字IN時, 會自動對值的類型進行轉換, 而後在進行操做. 在上面的狀況中SELECT name FROM orders,company WHERE orderID = 1 AND companyID IN (attachedCompanyIDs)
companyID IN ('1,2,3') ≡ companyID IN (CAST('1,2,3' AS INT)) ≡ companyID IN (1)
SELECT name FROM orders JOIN company ON companyID = ANY (('{' | attachedCompanyIDs | '}')::INT[]) WHERE orderID = 1可是MySQL暫不支持. 你能夠在這個連接裏面找到一些有趣的文章:
原文地址: http://stackoverflow.com/questions/4155873/find-in-set-vs-in