sql查询以查找所选文件的祖先

hl0ma9xz  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(285)

我有一个表,其中有3个字段,即id、filename和prev\u id,用于存储上传的文件

  1. Id | filename | prev_id
  2. ---------------------------
  3. 1 | file1 | NULL
  4. 2 | file2 | 1
  5. 3 | file3 | 2
  6. 4 | file4 | NULL
  7. 5 | file5 | 4
  8. 6 | file6 | 5

file3是最新上传的文件,而其他文件则是上一个用prev\u id标注的文件。我需要一个查询来列出file3以前的文件。像wise一样,另一个新上传的文件是file6。那什么时候
http://www.sqlfiddle.com/#!9/0e88c0/1号
预期产量
文件3以前的文件列表

  1. Id | filename
  2. ------------
  3. 1 | file1
  4. 2 | file2

文件6以前的文件列表

  1. Id | filename
  2. ------------
  3. 4 | file4
  4. 5 | file5
m2xkgtsf

m2xkgtsf1#

基于你方提供的(原始)样品

  1. id fname prev_id
  2. 1 file1 (null)
  3. 2 file2 1
  4. 3 file3 2
  5. 4 file4 (null)

您可以使用自连接,例如:

  1. select a.*
  2. from test_table a
  3. inner join test_table b on b.fname ='file3'
  4. and a.prev_id <= b.prev_id

http://www.sqlfiddle.com/#!9月9日EC606/21
a表重新运行file3的prev\u id,b表返回满足查询条件的值

展开查看全部
gudnpqoy

gudnpqoy2#

  1. select * from file where id < 14 ;

第一种方法是列出所有id小于 file3 正如你所说,它们已经分类了。
另一种方法是:(如果上传的文件有很多以前的记录,你可以限制它们)

  1. select * from file where id in (
  2. select id from file where id < 14
  3. ) order by id DESC limit 1;
xuo3flqw

xuo3flqw3#

这将为您提供结果,包括 file3 ```
select t1.id, t1.fname, @pv := t1.prev_id prev_id
from (select * from test_table order by id desc) t1
join (select @pv := 3) tmp // 3 is the id of file3
where t1.id = @pv;

  1. 裁判:https://stackoverflow.com/a/24901882/8317643
  2. 更新
  3. 结果没有 `file3` ```
  4. select (@pv := t1.prev_id) id, t1.fname
  5. from (select * from test_table order by id desc) t1
  6. join (
  7. select @pv := (
  8. select t4.prev_id
  9. from test_table t4
  10. where t4.id = 3
  11. )
  12. ) tmp
  13. where t1.id = @pv;
展开查看全部

相关问题