2014-01-28 129 views
1

我有兩個表,其中1個在不同日期有不同的值,另一個表決定我應該從第一個表中查找哪些數據。這裏有一個例子:多條件條款SQL

mysql> select * from test_table; 
+----+---------+---------------------+-------+ 
| id | test_id | ymd     | value | 
+----+---------+---------------------+-------+ 
| 1 |  1 | 2013-01-01 00:00:00 |  5 | 
| 2 |  1 | 2013-01-02 00:00:00 |  5 | 
| 3 |  1 | 2013-01-03 00:00:00 |  5 | 
| 4 |  2 | 2013-01-01 00:00:00 |  5 | 
| 5 |  2 | 2013-01-02 00:00:00 |  2 | 
| 6 |  2 | 2013-01-03 00:00:00 |  3 | 
| 7 |  2 | 2013-01-04 00:00:00 |  4 | 
| 8 |  2 | 2013-01-05 00:00:00 |  5 | 
| 9 |  3 | 2013-01-06 00:00:00 |  6 | 
+----+---------+---------------------+-------+ 

mysql> select * from test_ymd; 
+----+---------+---------------------+ 
| id | test_id | ymd     | 
+----+---------+---------------------+ 
| 1 |  1 | 2013-01-02 00:00:00 | 
| 2 |  2 | 2013-01-03 00:00:00 | 
+----+---------+---------------------+ 

我想寫這樣的查詢:

mysql-local> select * from test_table where (test_id=1 and ymd>'2013-01-02') or (test_id=2 and ymd>'2013-01-03'); 
+----+---------+---------------------+-------+ 
| id | test_id | ymd     | value | 
+----+---------+---------------------+-------+ 
| 3 |  1 | 2013-01-03 00:00:00 |  5 | 
| 7 |  2 | 2013-01-04 00:00:00 |  4 | 
| 8 |  2 | 2013-01-05 00:00:00 |  5 | 
+----+---------+---------------------+-------+ 

然而,對於一個大型#test_ids的,這顯然成爲毛利。有沒有一種快速簡單的方法在MySQL中執行此操作?

UPDATE

聯接是這樣做(感謝戈登)

mysql-local> select tt.* from test_table tt join test_ymd tymd on tt.test_id = tymd.test_id and tt.ymd > tymd.ymd; 
+----+---------+---------------------+-------+ 
| id | test_id | ymd     | value | 
+----+---------+---------------------+-------+ 
| 3 |  1 | 2013-01-03 00:00:00 |  5 | 
| 7 |  2 | 2013-01-04 00:00:00 |  4 | 
| 8 |  2 | 2013-01-05 00:00:00 |  5 | 
+----+---------+---------------------+-------+ 

我也很好奇一個好辦法,雖然關於是否有一種方法可以做到這一點的where子句。

回答

3

你想加入:

select tt.* 
from test_table tt join 
    test_ymd tymd 
    on tt.test_id = tymd.test_id and tt.ymd > tymd.ymd; 

編輯:

您可以用明確做加盟。一個典型的方法是使用exists

select tt.* 
from test_table tt 
where exists (select 1 
       from test_ymd tymd 
       where tt.test_id = tymd.test_id and tt.ymd > tymd.ymd 
      ); 

如果您有test_ymd(test_id, ymd)索引,那麼exists有優勢。如果您在test_ymd表中有一個id的重複行,則結果中沒有重複的危險。

+0

@crunkchitis。 。 。謝謝。 –

+0

謝謝,只是出於好奇,有沒有辦法在where子句中做,沒有連接? – crunkchitis

+0

感謝您的更新。 – crunkchitis

0

加入兩個表像

select temp.* from test_table temp join test_ymd temptymd 
on temp.test_id = temptymd.test_id and temp.ymd > temptymd.ymd;