SQL根据是否存在外键指向i的记录来选择查询记录

2024-09-27 00:14:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个“乘法器”表,它有一个外键“push\u id”,指向“pushs”表中的记录。这是一种多对一的关系。你知道吗

有些推送记录没有乘法器,但有些则有。我试图完成的是一个SQL查询,它选择具有乘数的最新push记录,然后查询乘数本身。你知道吗

比如:

push_id = result_of("SELECT id FROM pushes ORDER BY ID DESC LIMIT 1 WHERE <multiplier record exists where push_id == id>")

multipliers = result_of("SELECT * FROM multipliers LIMIT 1 WHERE push_id == push_id")

print(multipliers)

我可能还想在推送上添加一个约束。就像我只想要某一推的乘数。你知道吗

没有太多的SQL经验-任何帮助感谢。 谢谢。你知道吗

更新

我试过以下方法:

SELECT * from 
(
    select m.*, p.type,
    from multipliers m
    inner join pushes p
    on m.push_id = p.id
    where p.type = 'CONSTANT'
) AS res1 where res1.push_id = ( 
    select max(push_id) from    
        (
            select m.push_id
            from res1
        ) AS res2
);

我得到一个错误:

Error Code: 1146. Table 'res1' doesn't exist

Tags: offromidsql记录resultwhereselect
2条回答

也许是这样的?你知道吗

SELECT * FROM 
multipliers INNER JOIN pushes 
ON multipliers.push_id = pushes.push_id 
ORDER BY multipliers.push_id DESC 
LIMIT 1

INNER JOIN确保您正在从multiplier中选择数据,该push记录的数据集按最大的push_id排序。你知道吗

根据您的意见,有关“推送类型”的其他标准,您可以使用:

SELECT * FROM 
multipliers INNER JOIN pushes 
ON multipliers.push_id = pushes.push_id 
WHERE pushes.type = 'X'
ORDER BY multipliers.push_id DESC 
LIMIT 1


编辑:

更新问题后,您可能需要执行以下操作:

select m.*, p.type 
from multipliers m inner join pushes p on m.push_id = p.id
where m.push_id = 
(
    select max(m2.push_id)
    from multipliers m2 inner join pushes p2 on m2.push_id = p2.id
    where p2.type = 'CONSTANT'
)

由于您只对链接到乘数的推送感兴趣,因此可以在表之间不使用联接的情况下实现这一点。以下基于您自己尝试的查询演示了总体思路:

select *
from multipliers
where push_id is not null and
push_id = ( select max(push_id)
            from multipliers
          )

如果要按push类型进行约束,假设模型已规范化,仅在push表中包含该信息,则需要一个连接,例如:

select m.*
from multipliers m
inner join pushes p
on m.push_id = p.id
where p.type = 'Whatever push type'
and m.push_id = (
                  select max(push_id)
                  from multipliers
                );

EDIT based on new requirement in question to partition by push_type:

您可以使用嵌套的成员资格测试来扩展前面的查询,如下所示,以获得所需的结果

select m.*
from multipliers m
inner join pushes p
on m.push_id = p.id
where p.type = 'CONSTANT'
and m.push_id = (
                  select max(push_id)
                  from multipliers
                  where push_id in (
                                      select push_id
                                      from pushes
                                      where type = 'CONSTANT'
                                   )
                );

或者使用从初始查询派生的更简单的查询:

select *
from multipliers
where push_id = ( 
                  select max(push_id) 
                  from pushes 
                  where push_type = 'CONSTANT'
                ) 

相关问题 更多 >

    热门问题