2017-03-17 13 views
0

隨着表table1table2多個conditiions選擇需要選擇那些locationId S和hour S的table1的行,其中tiertable2high在其中

表1

+------------+------+---------+----------+ 
| locationId | hour | metric1 | metric2 | 
+------------+------+---------+----------+ 
|  1111 | 10 |  200 |  40 | 
|  1111 | 9 |  300 |  -20 | 
|  1111 | 11 | 1800 |  300 | 
|  1122 | 9 |  600 |  800 | 
|  1122 | 11 | 2300 |  -10 | 
|  1133 | 8 | 10000 |  30 | 
+------------+------+---------+----------+ 

表2

+------------+------+-------+---------+ 
| locationId | hour | value | tier | 
+------------+------+-------+---------+ 
|  1111 | 10 | 1300 | high | 
|  1111 | 9 | 900 | medium | 
|  1111 | 11 | 200 | low | 
|  1122 | 9 | 100 | low | 
|  1122 | 11 | 2300 | high | 
|  1133 | 8 | 1400 | high | 
+------------+------+-------+---------+ 

如果它是一列 - 說locationId我可以做類似

select * from table1 
where locationId in (select locationId from table2 where tier='high'); 

我如何做到這一點的時候了locationIdhour對需要進行比較?

輸出

+------------+------+---------+----------+ 
| locationId | hour | metric1 | metric2 | 
+------------+------+---------+----------+ 
|  1111 | 10 |  200 |  40 | 
|  1122 | 11 | 2300 |  -10 | 
|  1133 | 8 | 10000 |  30 | 
+------------+------+---------+----------+ 
+0

一種選擇是有一個字段'locationId_hour'這是'加入到'table2'and使用''locationId' hour' colums級聯select * from table1 where locationId ||小時(從table2中選擇locationId_hour,其中tier ='high')' – user3206440

回答

3

我認爲一個簡單的加入應該處理這個問題:

SELECT t1.* 
FROM table1 t1 
INNER JOIN table2 t2 
    ON t1.locationId = t2.locationId AND 
     t1.hour  = t2.hour 
WHERE t2.tier = 'high' 

輸出:

enter image description here

演示這裏:

Rextester

0

的INNER JOIN關鍵字只要有兩個表中的列之間的匹配選擇來自兩個表中的所有行。

select * from table1 t1 
inner join table2 t2 on t1.locationId =t2.locationId 
where t2.tier='high' 
+0

@ user3206440試試這個 – Faraz

0

使用EXISTS方法,讓您的結果:

SELECT * 
FROM table1 TBL1 WHERE EXISTS 
(
    SELECT 1 FROM table2 TBL2 WHERE TBL1.locationId = TBL2.locationId AND 
    TBL1.hour = TBL2.hour AND TBL2.tier = 'high' 
)