我正在处理我网站的照片部分,但更准确地说是在带有排序选项的下一个/上一个链接上。
存在两种不同的排序选项,首先有一个过滤器(最新、趋势、收藏、用户等),其次是一些先前过滤器的排序选项(日期、视图、评级等)
我很难找到一个好的解决方案来轻松检索我的幻灯片的下一张/上一张图片。
这是我用来获取下一张图片的一点点 SQLfilter:latest
if ($filter == "latest") {
$sql = "SELECT *
FROM photos
WHERE status = 0 AND id < ".$id."
ORDER BY id DESC
LIMIT 1
";
$result = $db->sql_query($sql);
$sql2 ="SELECT *
FROM photos
WHERE id = (SELECT MAX(id) FROM photos WHERE status = '0')
ORDER BY id DESC
LIMIT 1
";
}
我想知道在我的项目中是否有更简单的方法来实现它?也许存在一个 php 类来做这样的事情?
如果我必须这样做,我觉得我将花费很长时间让所有这些 SQL 查询正常工作。
编辑
这是我的photos
桌子的布局
`id` -> unique ID, autoincremented
`title`
`img_name` -> contains the image file name
`date_created` -> when the picture was uploaded
`uploader` -> id of the user that uploaded
`views` -> number of views the picture has
`up_votes` -> votes used to calculate the Wilson score interval
`down_votes`
`net_votes` -> up vote minus down votes
还有其他表格,例如将用户与他们拥有的朋友联系起来的表格,称为users_friends
`user_id` -> contains id of the user that added the friend
`friend_user_id` -> contains id of the friend in question
使用这两个表,我可以使用此 sql 查询获取用户朋友发布的所有图片:
SELECT *
FROM photos
WHERE uploader IN
(
SELECT friend_user_id
FROM users_friends
WHERE user_id = ':user_id'
)
ORDER BY id DESC
然后,我有两个查询来获取下一张图片的链接,还有两个其他查询来获取前一张图片的链接。我有两个,因为一个用于当您在数据库末尾返回另一端时,另一个用于所有其他查询。它们看起来像这样(我只在这里发布下一个按钮)
$sql = "SELECT *
FROM photos
WHERE status = 0 AND id < ".$id." AND Uploader IN (SELECT friend_user_id FROM users_friends WHERE user_id = ".$logedInUser['User_ID'].")
ORDER BY id DESC
LIMIT 1
";
$sql2 ="SELECT *
FROM photos
WHERE id = (SELECT MAX(id) FROM photos WHERE status = '0' AND Uploader IN (SELECT friend_user_id FROM users_friends WHERE user_id = ".$logedInUser['User_ID']."))
ORDER BY id DESC
LIMIT 1
";
$result = $db->sql_query($sql);
if (mysql_num_rows($result)==1) {
$row = $db->sql_fetchrow($result);
return "/photo/".$row["id"]."/".urlFriendly($row["Title"])."/".$filter.$sort;
}
else
{
$result = $db->sql_query($sql2);
$row = $db->sql_fetchrow($result);
return "/photo/".$row["id"]."/".urlFriendly($row["Title"])."/".$filter.sort;
}
我觉得有很多东西可以简化,但我还不知道该怎么做。
我也有威尔逊分数的下限sql代码来实现下一个/上一个按钮,而且要写4次是相当多的sql代码。也许我可以在photos
表中插入威尔逊分数,这可以简化很多 sql 代码。