Akshay Shah
Akshay Shah

Reputation: 490

Combining two SELECT queries from same table but different WHERE clause

I have a table named WORKOUTS having column named "install_time" and "local_id". Both are having column type integer. They are UNIQUE keys .I have written two queries like below :

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

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

Now I wanted to combine both these queries and one where clause to handle this condition but can't find a way for it.

EDIT

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

Upvotes: 1

Views: 3552

Answers (4)

Kashif
Kashif

Reputation: 105

It can be simply done as

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

Upvotes: 1

Mihail Shishkov
Mihail Shishkov

Reputation: 15857

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)

Also be careful when using the OR keyword. You have to put your parenthesis carefully.

Here is more info on the subject 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)
    )

Upvotes: 5

beane
beane

Reputation: 188

It depends what you mean by "combine both these queries". If you want a result set where the results of both the above queries are returned, you can try the OR operator. The following assumes that the date field is the same for both the local_ids.

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

Upvotes: 1

Sushil Mate
Sushil Mate

Reputation: 583

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

Upvotes: 3

Related Questions