我有两个表类别和照片
分类
CATEGORYID CATEGORY
-------------------
1 Nature
2 Animals
3 Travelling
4 Foods
照片
PHOTOID FILENAME CATEGORYID URL TIMEUPLOADED
------------------------------------------------------------------------------------------------
1001 file1.jpg 1 http://www.server.com/1001/file1.jpg 2015-12-25 19:21:22
1002 file2.jpg 1 http://www.server.com/1002/file2.jpg 2015-12-24 19:21:22
1003 file3.jpg 1 http://www.server.com/1003/file3.jpg 2015-12-22 19:21:22
1004 file4.jpg 2 http://www.server.com/1004/file4.jpg 2015-12-21 19:21:22
1005 file5.jpg 2 http://www.server.com/1005/file5.jpg 2015-12-20 19:21:22
1006 file6.jpg 3 http://www.server.com/1006/file6.jpg 2015-12-19 19:21:22
1007 file7.jpg 4 http://www.server.com/1007/file7.jpg 2015-12-18 19:21:22
1008 file8.jpg 3 http://www.server.com/1008/file8.jpg 2015-12-17 19:21:22
1009 file9.jpg 4 http://www.server.com/1009/file9.jpg 2015-12-16 19:21:22
我希望在相应类别中上传最新照片,其图像数量如下输出
PHOTOID FILENAME CATEGORYID CATEGORY URL TIMEUPLOADED IMGCOUNT
----------------------------------------------------------------------------------------------------------------------
1001 file1.jpg 1 Nature http://www.server.com/1001/file1.jpg 2015-12-25 19:21:22 3
1004 file4.jpg 2 Animals http://www.server.com/1004/file4.jpg 2015-12-21 19:21:22 2
1006 file6.jpg 3 Travelling http://www.server.com/1006/file6.jpg 2015-12-19 19:21:22 2
1007 file7.jpg 4 Foods http://www.server.com/1007/file7.jpg 2015-12-18 19:21:22 2
我尝试使用以下查询
SELECT t1.*,COUNT(*) AS IMGCOUNT FROM photos t1 GROUP BY CATEGORYID order by TIMEUPLOADED desc;
但它没有给出正确的结果
以下查询提供了各自上传的最新照片,但未提供图像计数
SELECT t1.*,COUNT(*) AS IMGCOUNT FROM photos t1
LEFT JOIN category t2 on t1.CATEGORYID = t2.CATEGORYID
JOIN (SELECT CATEGORYID, max(TIMEUPLOADED) maxdt FROM photos GROUP BY CATEGORYID) t3 ON t1.CATEGORYID = t3.CATEGORYID
AND t1.TIMEUPLOADED = maxdt
GROUP BY t1.CATEGORYID order by t1.TIMEUPLOADED desc;
答案 0 :(得分:1)
我认为这会有效..我创建了一个测试表并运行。您想要为给定类别发布最年轻的照片..以及该类别的总照片数量。
select
tmp.categoryid,
tmp.mycount,
tmp.maxpid,
p4.filename,
p4.url,
p4.timeuploaded
from
(select
p.categoryid,
count(p.photoid)as mycount,
(select max(photoid)
from test.photo p1
where p1.categoryid = p.categoryid and p1.timeuploaded = (
select max(p2.timeuploaded) from test.photo p2
where p.categoryid = p2.categoryid)) as maxpid
from test.photo p group by p.categoryid)
as tmp
join test.photo p4 on
p4.photoid = tmp.maxpid
答案 1 :(得分:0)
您无法根据需要执行查询,因为CATEGORYID包含多个具有不同PHOTOID的文件名。除非您想从这些类别中获得最小值或最大值:
select min(`PHOTOID`) as `PHOTOID`, min(`FILENAME`) as `FILENAME`,
`CATEGORYID`, min(`URL`) as `URL`, min(`TIMEUPLOADED`) as `TIMEUPLOADED`,
count(*) as 'IMGCOUNT'
from photos group by `CATEGORYID` order by `TIMEUPLOADED` desc;