gpt4 book ai didi

php - MySql 获取 id = xxx 且具有相同 id 的行中其他表中的最新列大于 1 的所有行

转载 作者:行者123 更新时间:2023-11-29 10:56:57 25 4
gpt4 key购买 nike

我有两个 mysql 表:tbl_posttbl_post_public

tbl_post 看起来像这样:

id | post_id   |  author  |  date (unix time)
--------------------------------
0 | xxxxx1 | User1 | 1489926071
1 | xxxxx2 | User2 | 1489926075
2 | xxxxx3 | User3 | 1489926079

此表包含用户的所有帖子

现在我有了tbl_post_public表:如果用户的帖子应该公开,则该表包含信息。如果用户从公共(public)更改为私有(private),则该行不会更新。它只是添加一个具有相同 post_id 但具有更新时间戳的新行0 = 公共(public) | 1 = 私有(private)

    id | post_id | public | date (unix time)
-----------------------------------------
--> 0 | xxxxx1 | 0 | 1489926071 <--| this two rows have the same
1 | xxxxx2 | 1 | | post_id but the second is
2 | xxxxx3 | 0 | | public = 1. i need to get
--> 3 | xxxxx1 | 1 | 1489926099 <--| the second row because its newer
^
|

所以,在结果中我想要有10行(LIMIT 10)按tbl_post DESC中的日期列排序,其中author =“User1”和最新的(tbl_post_public中的日期列) ) tbl_post_public 中的行(具有相同的 post_id)并且 public = 0

我希望你能理解我的问题并对我糟糕的英语表示歉意:)

最佳答案

您可以通过多种方式获取公共(public)表中的最新行。如果您要过滤帖子,我建议使用相关子查询:

select p.*
from (select p.*,
(select pp.public
from tbl_post_public pp
where pp.post_id = p.post_id
order by date desc
limit 1
) as latest_public
from tbl_post p
where . . .
) p
where public = 0
order by date desc
limit 10;

出于性能目的,您需要在 tbl_post_public(post_id, date) 上建立索引。

如果您没有 where 子句,并且在 tbl_post(date) 上有索引,那么这可能会更快一些:

select p.*
from (select p.*,
(select pp.public
from tbl_post_public pp
where pp.post_id = p.post_id
order by date desc
limit 1
) as latest_public
from tbl_post p
order by p.date desc
) p
where public = 0
limit 10;

关于php - MySql 获取 id = xxx 且具有相同 id 的行中其他表中的最新列大于 1 的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42886619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com