组合来自同一个表但不同WHERE子句的两个SELECT查询

时间:2016-04-21 06:40:36

标签: sql postgresql

我有一个名为WORKOUTS的表,其列名为" install_time"和" local_id"。两者都有列类型整数。它们是唯一的密钥。我写了两个如下的查询:

SELECT * from workouts where install_time = 123456 and local_id > 5

SELECT * from workouts where install_time = 987643 and local_id > 19

现在我想结合这些查询和一个where子句来处理这个条件,但是找不到办法。

修改

SELECT * from workouts where install_time = 123456 and local_id > 5 and date = xyz
SELECT * from workouts where install_time = 987643 and local_id > 19 and date = xyz

4 个答案:

答案 0 :(得分:4)

SELECT * 
FROM workouts 
WHERE 
    (install_time = 123456 AND local_id > 5 AND date = xyz)
    OR 
    (install_time = 987643 AND local_id > 19 AND date = xyz)

使用OR关键字时也要小心。你必须小心地放置括号。

以下是有关主题http://www.w3schools.com/sql/sql_and_or.asp

的更多信息
SELECT * 
FROM workouts 
WHERE 
    date = xyz
    AND (
      (install_time = 123456 AND local_id > 5)
      OR 
      (install_time = 987643 AND local_id > 19)
    )

答案 1 :(得分:3)

SELECT * from workouts where install_time = 123456 and local_id > 5 and date = xyz
Union
SELECT * from workouts where install_time = 987643 and local_id > 19 and date = xyz

答案 2 :(得分:1)

这取决于你的意思"结合这两个查询" 。如果您想要一个返回上述查询结果的结果集,您可以尝试使用OR运算符。以下假设date的{​​{1}}字段相同。

local_id

答案 3 :(得分:1)

可以简单地完成

SELECT * from workout where date=xyz and (install_time = 123456 and local_id > 5) or (install_time = 987643  and local_id> 19)