[英]mysql left outer join returns all rows, ignores specified field value
我在MySQL數據庫中有兩個表:
cellphone table
ID
phone_number
verification_code table
ID
verification_codes
code_expires
code_used
我正在嘗試在手機表格中查詢特定的ID,並且無論他們是否具有有效的驗證碼,我都希望獲得該行。
這是我的查詢
SELECT a.ID, a.phone_number, b.verification_code, b.code_expires
FROM cellphone a
LEFT OUTER JOIN verification_codes b ON (a.ID = b.ID
and a.ID = '12345'
and b.code_expires > NOW()
and b.code_used IS NULL)
我得到的是一個巨大的記錄集,其中包括所有ID號,而不僅僅是獲得我要查找的ID。 有人可以幫助我正確設置此查詢的格式嗎?
left join
第一個表的條件放在where
子句中。 條件在第二去on
:
SELECT c.ID, c.phone_number, vc.verification_code, vc.code_expires
FROM cellphone c LEFT OUTER JOIN
verification_codes vc
ON c.ID = vc.ID AND vc.code_expires > NOW() and vc.code_used IS NULL
WHERE c.ID = '12345'; -- single quotes are unnecessary if the id is a number
原因很簡單。 left join
將所有行保留在第一個表中,無論on
子句的計算結果為true,false還是NULL
。 即使對於第一張桌子上的條件也是如此。 因此,當left join
的第一個表中的條件位於on
子句中時,將被有效地忽略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.