SELECT *
FROM orders
WHERE date_ord >= '2015-02-16'
AND date_ord <= '2015-02-26'
AND active =1
AND (
(
ship_city = 'NYC'
OR ship_city = 'New York'
OR ship_city = 'New York City'
)
AND ship_state = 'NY'
)
OR (
(
bill_city = 'NYC'
OR bill_city = 'New York'
OR bill_city = 'New York City'
)
AND ship_state = ''
)
ORDER BY ordId
客户已添加&#34;纽约&#34;城市名称有三种变体,如&#34; NYC&#34;,&#34;纽约&#34;和#34;纽约市&#34;。我需要查询所有这些记录,其中结算城市是全部3种变化,并且运输状态为空或NULL,并且使用城市名称和运输状态的所有3种变体的运输城市是纽约的那些记录被设置为&#39; NY&#39 ;。简而言之,所有运往纽约市的订单。 (账单状态可以是CA或FL)
此查询并不完美。我的记录超过了日期范围。请建议修复此问题。
根据@Ash和@DovesandChicks的建议,我尝试使用IN函数
SELECT *
FROM orders
WHERE date_ord >= '2015-02-16'
AND date_ord <= '2015-02-26'
AND active =1
AND ship_city
IN ('NYC', 'New York', 'New York City')
OR (bill_city IN ('NYC', 'New York', 'New York City') AND ship_state = 'Unlisted')
ORDER BY ordId
查询仍有问题。请帮忙
答案 0 :(得分:1)
看起来你在OR附近有不必要的括号
SELECT *
FROM orders
WHERE date_ord >= '2015-02-16'
AND date_ord <= '2015-02-26'
AND active =1
AND (
(
ship_city = 'NYC'
OR ship_city = 'New York'
OR ship_city = 'New York City'
)
AND ship_state = 'NY'
--)
OR
--(
(
bill_city = 'NYC'
OR bill_city = 'New York'
OR bill_city = 'New York City'
)
AND ship_state = ''
)
ORDER BY ordId
通过适当的格式化,查询更具可读性
条件可以通过这种方式简化:
SELECT *
FROM orders
WHERE date_ord >= '2015-02-16'
AND date_ord <= '2015-02-26'
AND active =1
AND ship_city in ('NYC','New York','New York City')
AND ship_state in ('NY','')
ORDER BY ordId
答案 1 :(得分:1)
1)你可以使用
AND ship_city IN('NYC','New York','New York City')
2)你的OR条款没有足够的括号。您需要在一个括号中包含所有OR
所以
WHERE(日期位) AND(带有OR的城市位)
如果你需要我,我可以写出来:
SELECT * FROM tblorders
WHERE dateord >= '2015-02-16'
AND dateord <= '2015-02-26'
AND activeFlag =1
AND (s_city IN ( 'NYC', 'New York', 'New York City' ) OR ( b_city IN ( 'NYC', 'New York', 'New York City' ) AND s_state = 'Unlisted' ))
ORDER BY ordId