Hey Guys我很难将LIKE添加到我的UNION中,它似乎要么返回任何内容,要么只返回UNION中指定的项目,具体取决于我喜欢的位置,例如
完整查询
SELECT fruits.key,
region, location, report_date,
inspection_type AS type,
customer AS customer_name,
customer_number, shipper, po
FROM reports
JOIN ( ( SELECT `key` , `report_key`, `shipper`, `po`, `commodity`, `label`, `status`, `location` FROM `berries` )
UNION ( SELECT `key` , `report_key`, `shipper`, `po`, `commodity`, `label`, `status`, `location` FROM `melons` )
UNION ( SELECT `key` , `report_key`, `shipper`, `po`, `commodity`, `label`, `status`, `location` FROM `citrus` )
UNION ( SELECT `key` , `report_key`, `shipper`, `po`, `commodity`, `label`, `status`, `location` FROM `table_grapes` )
UNION ( SELECT `key` , `report_key`, `shipper`, `po`, `commodity`, `label`, `status`, `location` FROM `tree_fruit` )
UNION ( SELECT `key` , `report_key`, `shipper`, `po`, `commodity`, `label`, `status`, `location` FROM `lot` )
) fruits
ON inspection_number = fruits.report_key
WHERE fruits.status = '0' OR fruits.status = '1'
ORDER BY report_date DESC
返回
key region location report_date type customer_name customer_number shipper po
17 Great White North South Holywood 2012-10-21 citrus Name 206-420-9564 Yao Ming 4215
16 Great White North Boulder, CO 2012-10-21 citrus Name 206-420-9564 Hanjin 33215
21 nw 1969-12-31 citrus 2 321 sdfg sdfgs
20 nw sdfgsdfg 1969-12-31 citrus 2 321 sdfg sdfg
尝试这个
WHERE fruits.status = '0' OR fruits.status = '1' AND fruits.location LIKE '%Boulder%'
返回完全相同的内容,而不仅仅是位于Boulder
的行。
另一方面,这将返回行,但不会返回reports
`WHERE fruits.location LIKE'%Bolder%'AND fruits.status ='0'ORrruit.status ='1'
key region location report_date type customer_name customer_number shipper po
16 Great White North Boulder, CO 2012-10-21 citrus Jd Daniel 206-420-9564 Hanjin 33215
这样做的正确方法是什么?我似乎得到了一半,或者没有一个?
答案 0 :(得分:2)
你的问题是AND比OR绑定更难,这意味着你的where子句最终为
WHERE fruits.status = '0' OR
(fruits.status = '1' AND fruits.location LIKE '%Boulder%')
你的意思可能是
WHERE (fruits.status = '0' OR fruits.status = '1')
AND fruits.location LIKE '%Boulder%'
这意味着您必须在OR表达式周围添加括号。
答案 1 :(得分:1)
永远不要混淆ors和;而且没有在它们周围放置括号。这可能是你想要的:
WHERE (fruits.status = '0' OR fruits.status = '1') AND fruits.location LIKE '%Boulder%'
答案 2 :(得分:0)
我希望我明白你的意思。如果是这样,你需要主食:
WHERE fruits.status = '0' OR (fruits.status = '1' AND fruits.location LIKE '%Boulder%')
或
WHERE (fruits.status = '0' OR fruits.status = '1') AND fruits.location LIKE '%Boulder%'
希望有所帮助:)