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

时间:2017-03-19 12:33:11

标签: php mysql sql database

我有两个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表: 如果用户的帖子应该公开,则此表包含信息。 如果用户从公共更改为私有,则行剂量会更新。它只是添加了一个具有相同post_id但具有较新时间戳的新行 0 =公开| 1 =私人

    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) ORDERED by tbl_post中的日期列DESC WHERE author =&#34; User1&#34;和tbl_post_public中最新的(tbl_post_public中的日期列)行(具有相同的post_id)并且有public = 0

我希望你理解我的问题&amp;抱歉我的英语不好:)

1 个答案:

答案 0 :(得分:1)

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

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;