2016-04-21 156 views
1

我有一個名爲WORKOUTS的表,其中有名爲「install_time」和「local_id」的列。兩者都有列類型的整數。他們是。我已經寫了像下面兩個查詢唯一鍵:合併來自同一表但不同WHERE子句的兩個SELECT查詢

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 
+1

你有沒有試着用這兩個條件之間的'或'條件。 –

回答

1

更多信息這取決於你的的意思 「結合這兩個查詢」。如果您想要返回上述兩個查詢結果的結果集,則可以嘗試運算符OR。以下假定這兩個字段的date字段相同。

SELECT * FROM workouts 
WHERE date = xyz 
AND (
    (install_time = 123456 AND local_id > 5) 
    OR (install_time = 987643 AND local_id > 19) 
); 
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) 

使用或關鍵字時,也要小心。你必須小心地放置括號。

下面是關於這個問題的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) 
    ) 
+0

我編輯了我的問題。我忘了提及日期字段。 –

+1

是的,你可以。如果兩種情況下的日期相同,則可以預先提取。但正如我所說,你必須小心括號。 –

+0

雖然這不是Postgre相關的,你可以檢查這個邏輯運算符優先 - > https://technet.microsoft.com/en-us/library/ms186992(v=sql.105).aspx –

2
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 
1

可以做簡單的

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