SELECT 使用 LEFT JOIN 后未应用 WHERE 过滤器

SELECT WHERE filter is not applied after using a LEFT JOIN

假设我有三个表 transactionsitemsusers,看起来像这样

#items

id  brand  price   transaction_id
--+------+-------+---------------
1  apple    10          1
2  apple    20          2
3  pear     15          1
4  banana   20          1
#transactions
id   user_id
--+------+
1    1    
2    1  
3    2
4    1
#users

id   system   value
---+---------+-------
1    gooogle   001
1    facebook  jashd28
2    google    002
2    facebook  jlak30

然后我想将这些连接在一起,这样我就可以看到哪些 (google) 用户购买了哪些品牌。目前我的查询看起来像

SELECT items.transaction_id,items.brand,users.value, items.price  FROM items
LEFT JOIN transactions 
    ON transactions.id= items.transactions_id
LEFT JOIN users
    ON users.id=transactions.user_id
    AND users.system='google'
WHERE items.transaction_id=1
AND LOWER(items.brand) LIKE '%apple%' OR LOWER(items.brand) LIKE '%pear%'

(上面的查询和我的不是100%一样,但是结构是一样的;多个join,最后一个WHERE子句)

但它 return 是 transaction_id 而不是 1。我可以将 items.transaction_id 放入 JOIN 但似乎 return 来自 transaction_id=1 的所有项目而不是 applepear

预计:

id brand price user
--+-----+-----+-----
1  apple  10    001
3  pear   15    001

结果:

id brand price user
--+-----+-----+-----
1  apple  10    001
2  apple  20    002  #<- should not be there since it does not have transaction_id=1
3  pear   15    001
4  banana 20    001    

您的声明如下:

SELECT items.transaction_id,items.brand,users.value, items.price  FROM items
LEFT JOIN transactions 
    ON transactions.id= items.transactions_id
LEFT JOIN users
    ON users.id=transactions.user_id
    AND users.value='google'
WHERE items.transaction_id=1
AND LOWER(items.brand) LIKE '%apple%' OR LOWER(items.brand) LIKE '%pear%'

您的问题是它显示的值没有 items.transaction_id = 1

原因是因为您混淆了 ANDOR SQL 限定符,并且因为您没有正确地括起来( 和括号 ) 他们的顺序很重要,所以你实际上在做:

WHERE (
       items.transaction_id=1
    AND 
       LOWER(items.brand) LIKE '%apple%'
     )
 OR LOWER(items.brand) LIKE '%pear%'

您的 AND 语句应该使用 圆括号 因为您有一个 OR 限定词;所以需要构造AND ( x OR z )

的语法逻辑

所以:

WHERE items.transaction_id=1
    AND ( LOWER(items.brand) LIKE '%apple%' 
          OR LOWER(items.brand) LIKE '%pear%')

正如 Martin 在上述问题中提到的,一个问题是缺少括号。 其次,除了 JOIN 之外,您还需要 where 条件。 所以最终查询将是

select distinct i.id, i.brand, i.price, u.value from items i
left join transactions t
on i.transaction_id = t.Id
left join users u 
on u.ID2 = t.user_id 
where i.transaction_id = 1 
and (i.brand like '%apple%' or i.brand like '%pear%')
and u.system = 'google'