duanliang8464 2011-11-25 13:51
浏览 16
已采纳

如何减少规范化数据库中的查询数量?

Imagine a table for articles. In addition to the main query:

SELECT * From articles WHERE article_id='$id'

We also need several other queries to get

SELECT * FROM users WHERE user_id='$author_id' // Taken from main query

SELECT tags.tag 
FROM tags 
  INNER JOIN tag_map 
    ON tags.tag_id=tag_map.tag_id 
WHERE article_id='$id'

and several more queries for categories, similar articles, etc

Question 1: Is it the best way to perform these queries separately with PHP and handle the given results, or there is way to combine them?

Question 2: In the absence of many-to-many relationships (e.g. one tag, category, author for every article identified by tag_id, category_id, author_id); What the best (fastest) was to retrieve data from the tables.

  • 写回答

3条回答 默认 最新

  • dougongnan2167 2011-11-25 13:57
    关注

    If all the relationships are one-many then you could quite easily retrieve all this data in one query such as

    SELECT
        [fields required]
    FROM
        articles a
        INNER JOIN
            users u ON a.author_id=u.user_id
        INNER JOIN 
            tag_map tm ON tm.article_id=a.article_id
        INNER JOIN
            tags t t.tag_id=tm.tag_id
    WHERE
        a.article_id='$id'
    

    This would usually be faster than the three queries separately along as your tables are indexed correctly as MySQL is built to do this! It would save on two round trips to the database and the associated overhead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题