nkh*_*uyu 1 sql sql-server where-clause where-in sql-in
我有一张桌子如下.
id date value
1 2011-10-01 xx
1 2011-10-02 xx
...
1000000 2011-10-01 xx
Run Code Online (Sandbox Code Playgroud)
然后我有1000个ID,每个人都有一个约会.我想执行以下操作:
SELECT id, date, value
FROM the table
WHERE (id, date) IN ((id1, <= date1), (id2, <= date2), (id1000, <= date1000))
Run Code Online (Sandbox Code Playgroud)
实现上述查询的最佳方法是什么?
您没有指定DBMS,因此这是标准SQL.
你可以这样做:
with list_of_dates (id, dt) as (
values
(1, date '2016-01-01'),
(2, date '2016-01-02'),
(3, date '2016-01-03')
)
select
from the_table t
join list_of_dates ld on t.id = ld.id and t.the_date <= ld.dt;
Run Code Online (Sandbox Code Playgroud)
这假设您在日期列表中没有重复项.
更新 - 现在DBMS已被披露.
对于SQL Server,您需要将其更改为:
with list_of_dates (id, dt) as (
values
select 1, cast('20160101' as datetime) union all
select 2, cast('20160102' as datetime) union all
select 3, cast('20160103' as datetime)
)
select
from the_table t
join list_of_dates ld on t.id = ld.id and t.the_date <= ld.dt;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
219 次 |
| 最近记录: |