PHP+MySQL用户收藏内容读取:如何高效获取并排序收藏标题?(收藏.高效.排序.读取.获取...)
php mysql 读取用户收藏内容优化
用户收藏是网站常见的功能。以商品和文章为例,涉及三个数据表:favorites(收藏数据)、goods(商品)和 articles(文章)。
要在收藏列表中获取收藏内容的标题,有两种方法:
方法一:foreach 循环
if ($type == 1) { $sql = "select * from goods where id = $value['cid'];"; }
方法二:批量查询
$array_goods = []; $array_articles = []; foreach ($favorites as $favorite) { if ($favorite['type'] == 1) { $array_goods[] = $favorite['cid']; } else { $array_articles[] = $favorite['cid']; } } $sql_goods = "select * from goods where id in ($array_goods);"; $sql_articles = "select * from articles where id in ($array_articles);";
方法二效率更高,但排序问题难解决
方法二效率更高,但组合标题后无法按照 favorites 表中的 dateline 排序。
优化方案:联表查询
SELECT IF(goods.id IS NULL, articles.title, goods.title), favorites.* FROM favorites LEFT JOIN goods ON goods.id = favorites.cid AND favorites.type = 1 LEFT JOIN articles ON articles.id = favorites.cid AND favorites.type = 2 ORDER BY dateline DESC;
此方案直接联表查询,并使用 if 函数处理标题。该方案无需考虑排序问题,效率也很高。
如果收藏类型较多,可以使用 case then 语句处理。
以上就是PHP+MySQL用户收藏内容读取:如何高效获取并排序收藏标题?的详细内容,更多请关注知识资源分享宝库其它相关文章!