哪里有不同的条件

时间:2017-06-16 08:50:50

标签: sql

我有一张桌子,想要使用where执行以下操作。我想选择NUM_ORDERS = 1 CHANNEL_ID in (1,2,3,4)所有行以及NUM_ORDERS > 1CHANNEL_ID in (1,2,3)所有行。我如何结合这两个条件?

感谢您的帮助。

4 个答案:

答案 0 :(得分:5)

以下SQL查询应该这样做。请注意,由于运算符优先级,我在where子句中使用的括号不是必需的。

 SELECT *
    FROM [put_your_table_here]
    WHERE (NUM_ORDERS = 1 AND CHANNEL_ID IN (1,2,3,4)) OR (NUM_ORDERS > 1 AND CHANNEL_ID IN (1,2,3))

答案 1 :(得分:3)

您可以使用UNION,它结合了查询#1和查询#2的结果。

select * from [table] where NUM_ORDERS = 1 AND CHANNEL_ID in (1,2,3,4) 
UNION
select * from [table] where NUM_ORDERS > 1 AND CHANNEL_ID in (1,2,3);

默认情况下,UNION运算符仅选择不同的值。要允许重复值,请使用UNION ALL

select * from [table] where NUM_ORDERS = 1 AND CHANNEL_ID in (1,2,3,4) 
UNION ALL
select * from [table] where NUM_ORDERS > 1 AND CHANNEL_ID in (1,2,3);

另一个更好的解决方案是使用像这样的OR子句;

SELECT * from [table] where (NUM_ORDERS = 1 AND CHANNEL_ID in (1,2,3,4)) or (NUM_ORDERS > 1 and CHANNEL_ID in (1,2,3));

答案 2 :(得分:3)

您有几个选择:

使用OR:

SELECT...
WHERE (NUM_ORDERS = 1 AND CHANNEL_ID in (1,2,3,4))
OR
(NUM_ORDERS > 1 and CHANNEL_ID in (1,2,3))

或者,将两者联合起来:

SELECT...
WHERE NUM_ORDERS = 1 AND CHANNEL_ID in (1,2,3,4)
UNION
SELECT...
WHERE NUM_ORDERS > 1 and CHANNEL_ID in (1,2,3)

答案 3 :(得分:1)

这将是这样的:

SELECT * 
FROM tableName
WHERE (NUM_ORDERS = 1 AND CHANNEL_ID IN (1,2,3,4))
OR (NUM_ORDERS > 1 AND CHANNEL_ID IN (1,2,3))