php - 编写更好的代码/查询

标签 php mysql performance loops while-loop

在我的网站上,用户可以更新,其他人可以对更新发表评论,就像其他社交网站一样..

在做什么:

query = fetches first name, last name, user id, update id, update post UNION same details for the user who has logged in i.e /* Updates Of Current Logged In User + Updates Of People He Is Following */

loop {
prints first name last name and update
}

后来我引入了评论功能,所以现在我所做的是在循环中调用查询并再次运行循环以获取评论..

loop {
prints first name last name and update

commentquery = fetches firstname, last name, user id, comment, of the particulat post
    again loop {
         prints first/last name of the person who commented, and his comment
     }
}

根据我的看法,我想这可以通过 SQL 查询来完成,当我检索帖子时,我可以连同它的评论一起获取,或者这是正确的方法吗?问题是当外循环运行时,内循环也会运行以获取适当的评论,所以我可以加入表以检索与帖子/更新相关的评论吗?

最佳答案

如果没有您的数据库结构或实际的 SQL,这很难回答,但我已尝试尽可能概括。您尝试做的事情应该通过 SQL 使用两个查询和一个循环来完成,如下所示。

编辑 您的精细循环并重新执行查询。您可以使用 SQL 一次性获取所有这些数据,但您将在每次调用中重复分配信息。为了可扩展性和可读性,我会坚持使用两个查询和两个循环

/** updated after op's comments **/

SELECT data, that, you, want, for, one, post
FROM posts AS a
INNER JOIN users AS b ON b.id = a.user_id

loop over query results () {

    /** output the post data **/

    /** Then select the users who have posted on this post **/
    SELECT a.comments, b.username
    FROM comments AS a
    INNER JOIN users AS b ON b.id = a.id
    INNER JOIN posts AS c ON c.id = a.post_id AND c.post_id = '[post id value]'
    ORDER BY a.date_posted;

    loop comments here {
      /** output comments here **/
    }
}

关于php - 编写更好的代码/查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12582398/

相关文章:

php - 使用 PHP/Drupal 处理大型数据集

php - 用输入框更新MySQL -- PHP MYSQL HTML

mysql - 如何为mysql中的每个组赋予相同的值

sql - SQL中如何连接多个select语句

php - jQuery 通过 $.post 触发点击

PHP PDO rowCount() 如何得到它的结果?

php - 服务器需要很长时间才能响应

sql - 如何避免在 postgresql 中执行查询期间出现空间问题?

python - 在 Python 中从列表中弹出元素的时间复杂度是多少?

php - 如何更改登录位置或注册成功消息?