[英]How to get latest posts from each category
I create a website with PHP and MySQL, I have a table with the following rows ID - POST TITLE - CATEGORY. 我使用PHP和MySQL创建了一个网站,我有一个表,其中包含以下行ID-POST TITLE-CATEGORY。 right now I have 10 posts published on three different categories (sport, health, world) and I want a sql allows me to get the latest post from each category.
现在我有10个帖子发布在三个不同的类别(体育,健康,世界)上,并且我希望SQL允许我从每个类别中获取最新帖子。
I tried this 我试过了
<?php
$scat_sql = mysql_query("select * from videos where category = 'sport' order by id desc limit 1");
while($scat_row = mysql_fetch_assoc($scat_sql)){
$scat_link = $scat_row['post title'];
}
?>
but the problem is I need to repeat this code for each category. 但是问题是我需要为每个类别重复此代码。 The output that I want looks like this :
我想要的输出看起来像这样:
The latest post of health category 最新健康类别
The latest post of sport category 最新体育类帖子
The latest post of world category 世界类别的最新文章
I would add a datetime
field to the table if you don't already have that, something like date_posted
. 如果您还没有
datetime
字段,我会在表中添加它,例如date_posted
。 When you add a new post, insert the current date and time into date_posted
along with the other fields. 添加新帖子时,将当前日期和时间以及其他字段插入
date_posted
。
When you want the three latest posts in each category, you can use a group by
statement along with the min
function on date_posted
. 当您需要每个类别中的三个最新帖子时,可以使用
group by
语句以及date_posted
上的min
函数。
select * from videos
inner join (
select min(date_posted) date_posted from videos group by category
) recent on (recent.date_posted = videos.date_posted);
The select in the inner join gets the most recent date_posted for each category. 内部联接中的选择将获取每个类别的最新date_posted。 The inner join matches and joins that date_posted with the correct row to get the other values.
内部联接将date_posted与正确的行匹配并联接以获取其他值。
$command = "SELECT * FROM videos WHERE category='sport' ORDER BY id DESC LIMIT 1";
$result = mysql_query ($command) or die ("<strong>Error:</strong> ". mysql_error());
while ($row = mysql_fetch_array ($result))
{
echo $row[name_of_the_column_you_want_to_echo];
};
That should do it. 那应该做。
If you simply want to shorten your code you could insert your categories (tables) into a array or a another table. 如果只想缩短代码,则可以将类别(表)插入数组或另一个表中。 Read out that table or array in a loop and make the table in your query a variable.
循环读取该表或数组,并使查询中的表成为变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.