【发布时间】:2022-01-05 13:45:11
【问题描述】:
假设我有三个表 transactions、items 和 users,看起来像这样
#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
然后我想将它们连接在一起,这样我就可以看到哪个(谷歌)用户购买了哪些品牌。目前我的查询看起来像
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子句)
但它返回 transaction_id 而不是 1。我可以将 items.transaction_id 放入 JOIN 中,但它似乎从 transaction_id=1 返回所有项目,而不是 apple 或 pear
预期:
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
【问题讨论】:
-
使用括号:
AND (LOWER(items.brand) LIKE '%apple%' OR LOWER(items.brand) LIKE '%pear%') -
@forpas pfft, perentheses; “括号”的时髦术语啊哈哈哈哈 :-) 编辑我的答案听起来更聪明