美文网首页
Postgres 复杂连表查询

Postgres 复杂连表查询

作者: Lupino | 来源:发表于2020-12-23 23:35 被阅读0次

首先我们建立四张表,如下

CREATE TABLE blocks (
    file_id bigint NOT NULL,
    proj_id integer NOT NULL,
    block_id bigint NOT NULL,
);
CREATE TABLE files (
    proj_id integer NOT NULL,
    file_id bigint NOT NULL,
    file_path text,
    file_hash character varying(64),
);
CREATE TABLE projs (
    proj_id integer NOT NULL,
    proj_path text,
);
CREATE TABLE results (
    id bigint NOT NULL,
    proj_id0 integer NOT NULL,
    block_id0 bigint NOT NULL,
    proj_id1 integer NOT NULL,
    block_id1 bigint NOT NULL
);

results 是我们数据结果的表
查找表 results 如下:

select * from results limit 10;

现在需要把 proj_path 添加到输出结果上,分别 proj0_path, proj1_path

select 
    r.*, 
    proj0.proj_path as proj_path0, 
    proj1.proj_path as proj_path0,
from 
    resuts as r,
    projs as proj0, 
    projs as proj1 
where 
    proj0.proj_id=r.proj_id0 
and 
    proj1.proj_id=r.proj_id1
limit 1

把 file_id 添加到输出结果上, 分别 file_id0, file_id1。

select 
    r.*, 
    proj0.proj_path as proj_path0, 
    proj1.proj_path as proj_path0,
    block0.file_id as file_id0,
    block1.file_id as file_id1
from 
    resuts as r,
    projs as proj0, 
    projs as proj1,
    blocks as block0,
    blocks as block1
where 
    proj0.proj_id=r.proj_id0 
and 
    proj1.proj_id=r.proj_id1
and 
    block0.block_id=r.block_id0
and 
    block1.block_id=r.block_id1
limit 1

把 file_path 添加到输出结果上, 分别 file_path0, file_path1。

select 
    r.*, 
    proj0.proj_path as proj_path0, 
    proj1.proj_path as proj_path0,
    block0.file_id as file_id0,
    block1.file_id as file_id1,
    file0.file_path as file_path0,
    file1.file_path as file_path1
from 
    resuts as r,
    projs as proj0, 
    projs as proj1,
    blocks as block0,
    blocks as block1,
    files as file0,
    files as file1
where 
    proj0.proj_id=r.proj_id0 
and 
    proj1.proj_id=r.proj_id1
and 
    block0.block_id=r.block_id0
and 
    block1.block_id=r.block_id1
and
    file0.file_id=block0.file_id
and
    file1.file_id=block1.file_id
limit 1

到此就出我们想要的结果

相关文章

  • Postgres 复杂连表查询

    首先我们建立四张表,如下 results 是我们数据结果的表查找表 results 如下: 现在需要把 proj_...

  • sql _ 连表查询 & 授权

    一,连表查询 1)连表 简单查询_where 2) 连表 多种方式查询 3)子查询 综合以上查询示例 二,DCL数...

  • 连表查询

    看上一篇帖子的表结构

  • SQL语句集锦

    携带条件连表子查询(条件查询表b后的结果用来查询表a):SELECT a.* FROM 表a AS a INNE...

  • 2021-08-29

    数据模型: 插入数据: 查询数据: 两表,连查询研究: 单表查询研究: 结果; 三表联查 结果: 项目思路:"""...

  • JdbcTemplate

    查询操作 复杂查询 复杂查询二:查询出来后封装为实体对象(通过RowMapper将类的属性与表的字段进行映射) 使...

  • mybatis连表查询

    大家好,我是IT修真院武汉分院第11期学员,一枚正直善良的java程序员。今天给大家分享一下,任务拓展:maven...

  • SQL连表查询

    连接查询包括合并、内连接、外连接和交叉连接,如果涉及多表查询,了解这些连接的特点很重要。 1、Union UNIO...

  • 连表查询实例

    查询是酸奶的商品信息(查完一张表,用返回值再去查另外一张表) 连表查询

  • mysql连表查询

    1. 交叉连接 (cross join) 假设有t1和t2两张表,交叉连接最简单的即是select * from ...

网友评论

      本文标题:Postgres 复杂连表查询

      本文链接:https://www.haomeiwen.com/subject/vpkpnktx.html