
php mysql 读取用户收藏内容优化
用户收藏是网站常见的功能。以商品和文章为例,涉及三个数据表:favorites(收藏数据)、goods(商品)和 articles(文章)。
要在收藏列表中获取收藏内容的标题,有两种方法:
方法一:foreach 循环
立即学习“PHP免费学习笔记(深入)”;
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用户收藏内容读取:如何高效获取并排序收藏标题?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号