SQLite 中的多个子查询条件或循环
Multiple subquery criteria or looping in SQLite
是否可以在单个 SQL 语句中执行类似“foreach”的查询?我的具体实现是使用SQLite,所以建议语法兼容。
示例:假设我们有一个 table 类似于以下内容:
simulation_id | sprite_id | time | x | y
1 1 0.0 0.0 0.0
1 2 0.0 5.5 1.6
1 1 1.0 0.1 0.0
1 2 1.0 5.5 1.5
1 3 1.0 9.9 4.1
1 1 2.0 ...
1 2 2.0
1 3 2.0
2 1 0.0
2 1 1.0
2 1 2.0
2 2 2.0
2 1 3.0
2 2 3.0
2 3 3.0
...
table 的关键要点是并非所有“sprite_id”条目都可以在 t=0.0 时实例化。
我想在第一个实例中检索所有精灵的位置 sprite_id=3 出现在每个模拟中。因此,我的理想查询将检索精灵 1、2 和 3 在 simulation_id=1 的 t=1.0 和 simulation_id=2.
的 t=3.0 的位置
我相信查询会是这样的:
SELECT simulation_id, sprite_id, time, x, y
FROM locations WHERE time = (SELECT MIN(time) FROM locations WHERE sprite_id = 3)
...但是我需要这个 运行 用于 table 中的每个 simulation_id;这甚至可以在单个 SQL 查询中实现吗?
您可以在 WHERE
子句中使用相关子查询:
SELECT l.*
FROM locations l
WHERE l.sprite_id = 3
AND time = (
SELECT MIN(time)
FROM locations
WHERE simulation_id = l.simulation_id AND sprite_id = l.sprite_id
)
或者用ROW_NUMBER()
window函数:
SELECT simulation_id, sprite_id, time, x, y
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY simulation_id ORDER BY time) rn
FROM locations
WHERE sprite_id = 3
)
WHERE rn = 1
参见demo。
结果:
> simulation_id | sprite_id | time | x | y
> ------------: | --------: | ---: | :--- | :---
> 1 | 3 | 1.0 | .... | ....
> 2 | 3 | 3.0 | .... | ....
是否可以在单个 SQL 语句中执行类似“foreach”的查询?我的具体实现是使用SQLite,所以建议语法兼容。
示例:假设我们有一个 table 类似于以下内容:
simulation_id | sprite_id | time | x | y
1 1 0.0 0.0 0.0
1 2 0.0 5.5 1.6
1 1 1.0 0.1 0.0
1 2 1.0 5.5 1.5
1 3 1.0 9.9 4.1
1 1 2.0 ...
1 2 2.0
1 3 2.0
2 1 0.0
2 1 1.0
2 1 2.0
2 2 2.0
2 1 3.0
2 2 3.0
2 3 3.0
...
table 的关键要点是并非所有“sprite_id”条目都可以在 t=0.0 时实例化。
我想在第一个实例中检索所有精灵的位置 sprite_id=3 出现在每个模拟中。因此,我的理想查询将检索精灵 1、2 和 3 在 simulation_id=1 的 t=1.0 和 simulation_id=2.
的 t=3.0 的位置我相信查询会是这样的:
SELECT simulation_id, sprite_id, time, x, y
FROM locations WHERE time = (SELECT MIN(time) FROM locations WHERE sprite_id = 3)
...但是我需要这个 运行 用于 table 中的每个 simulation_id;这甚至可以在单个 SQL 查询中实现吗?
您可以在 WHERE
子句中使用相关子查询:
SELECT l.*
FROM locations l
WHERE l.sprite_id = 3
AND time = (
SELECT MIN(time)
FROM locations
WHERE simulation_id = l.simulation_id AND sprite_id = l.sprite_id
)
或者用ROW_NUMBER()
window函数:
SELECT simulation_id, sprite_id, time, x, y
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY simulation_id ORDER BY time) rn
FROM locations
WHERE sprite_id = 3
)
WHERE rn = 1
参见demo。
结果:
> simulation_id | sprite_id | time | x | y
> ------------: | --------: | ---: | :--- | :---
> 1 | 3 | 1.0 | .... | ....
> 2 | 3 | 3.0 | .... | ....