我们在MySQL中有一个表,其中一列是date_added
。
对于每个date_added
,可能有几条记录。
我需要显示一个网页,其中显示按日期降序排序的行,但每个日期最多只有10个。
示例输出:
Jun 1
item
item
item
item
item
item
May 31
item
item etc
有没有办法在MySQL中运行一个可以获取这样结果的查询?
答案 0 :(得分:1)
SELECT * FROM records WHERE date_added in (
SELECT date_added FROM dates ORDER BY date_added DESC
)
就我的知识有限而言,每个日期不能只选择10行。您需要在应用的业务逻辑中强制执行该限制。
答案 1 :(得分:0)
我不确定我到底知道你在追求什么,但你可以尝试:
SELECT * FROM myTable GROUP BY date_added DESC LIMIT 0,10;
答案 2 :(得分:0)
据我所知,无法通过查询完成。唯一的解决方案是将此逻辑放入网页的代码中。
确保记录集按日期排序。
在PHP中,一个选项是:
foreach ($rs as $row)
{
if ($tmp_date != $row->date_added) { $counter = 0; }
if ($counter <= 10) {
echo $row->yourinfo; //Whatever you want echoed from your recordset
}
$counter++;
$tmp_date = $row->date_added;
}
答案 3 :(得分:0)
不确定性能(可能不好):
SELECT m.*
FROM
myTable AS m
WHERE m.id IN
( SELECT ms.id
FROM myTable AS ms
WHERE ms.date_added = m.date_added
ORDER BY ms.something ASC --- whatever (ASC or DESC)
LIMIT 10
)
ORDER BY m.date_added
, m.something
你也可以试试这个:
SELECT m1.*
FROM myTable AS m1
JOIN myTable AS m2
ON m2.date_added = m1.date_added
AND m2.id <= m1.id --- this could also be:
--- m2.someField <= m1.someField
GROUP BY m1.id
HAVING COUNT(*) <= 10
ORDER BY m.date_added
或变体:
SELECT m1.*
FROM myTable AS m1
LEFT JOIN myTable AS m2
ON m2.date_added = m1.date_added
AND m2.id < m1.id
GROUP BY m1.id
HAVING COUNT(*) < 10
ORDER BY m.date_added
答案 4 :(得分:0)
SET @rank:=0;
select TTT.f1, TTT.value
from
(select TT.f1, TT.value,TT.c,
@rank:=@rank+1 as rnk,
case when @rank>=TT.c then @rank:=0 end as dummy
from (
select T.f1, T.value, cnt.c
from t2 T, (select f1, count(*) as c from t2 group by f1) cnt
where cnt.f1 = T.f1
order by T.f1 asc, T.value desc) TT ) TTT
where TTT.rnk<=10
其中f1
是'date'字段,value
是'item'字段