繁体   English   中英

条件SQL的多条件条件

[英]Multiple Conditional Where Clause 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子句中做到这一点。

你想要一个加入:

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的重复行, test_ymd存在在结果中获得重复的危险。

像两个表一样加入

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM