schema.rb

  1. ActiveRecord::Schema.define(version: 20150203032005) do
  2.  
  3. create_table "addresses", force: true do |t|
  4. t.integer "client_id"
  5. t.string "street"
  6. t.string "postcode"
  7. t.datetime "created_at"
  8. t.datetime "updated_at"
  9. end
  10.  
  11. create_table "clients", force: true do |t|
  12. t.string "name"
  13. t.string "gender"
  14. t.datetime "created_at"
  15. t.datetime "updated_at"
  16. end
  17.  
  18. create_table "infos", force: true do |t|
  19. t.integer "address_id"
  20. t.string "history"
  21. t.datetime "created_at"
  22. t.datetime "updated_at"
  23. end
  24.  
  25. end

client.rb

  1. class Client < ActiveRecord::Base
  2. has_one :address
  3. end

address.rb

  1. class Address < ActiveRecord::Base
  2. belongs_to :client
  3. has_many :infos
  4. end

info.rb

  1. class Address < ActiveRecord::Base
  2. belongs_to :client
  3. has_many :infos
  4. end

Client.all

  1. Client Load (0.4ms) SELECT "clients".* FROM "clients"
  2. => #<ActiveRecord::Relation [#<Client id: 1, name: "wei", gender: "1", created_at: "2015-02-03 02:12:36", updated_at: "2015-02-03 02:12:36">, #<Client id: 2, name: "yan", gender: "1", created_at: "2015-02-03 02:48:11", updated_at: "2015-02-03 02:48:11">]>

Address.all

  1. SELECT "addresses".* FROM "addresses"
  2. => #<ActiveRecord::Relation [#<Address id: 1, client_id: 1, street: "huanyuan", postcode: "123456", created_at: "2015-02-03 02:13:45", updated_at: "2015-02-03 02:13:45">, #<Address id: 2, client_id: 2, street: "huayuan", postcode: "23456", created_at: "2015-02-03 02:50:12", updated_at: "2015-02-03 02:50:12">]>

Info.all

  1. SELECT "infos".* FROM "infos"
  2. => #<ActiveRecord::Relation
    [#<Info id: 1, address_id: 1, history: "1110", created_at: "2015-02-03 03:25:34", updated_at: "2015-02-03 03:25:34">,
  3. #<Info id: 2, address_id: 1, history: "1111", created_at: "2015-02-03 03:26:16", updated_at: "2015-02-03 03:26:16">,
  4. #<Info id: 3, address_id: 1, history: "1112", created_at: "2015-02-03 03:26:21", updated_at: "2015-02-03 03:26:21">,
  5. #<Info id: 4, address_id: 2, history: "2110", created_at: "2015-02-03 03:26:32", updated_at: "2015-02-03 03:26:32">,
  6. #<Info id: 5, address_id: 2, history: "2111", created_at: "2015-02-03 03:26:34", updated_at: "2015-02-03 03:26:34">,
  7. #<Info id: 6, address_id: 2, history: "2112", created_at: "2015-02-03 03:26:37", updated_at: "2015-02-03 03:26:37">,
  8. #<Info id: 7, address_id: 2, history: "2113", created_at: "2015-02-03 03:26:39", updated_at: "2015-02-03 03:26:39">]>

  

N + 1 查询的解决办法

  1. clients = Client.limit(2)
  2.  
  3. clients.each do |client|
  4. puts client.address.postcode
  5. end

生成的sql语句为:

  1. SELECT "clients".* FROM "clients"
  2. => #<ActiveRecord::Relation
  3. [#<Client id: 1, name: "wei", gender: "1", created_at: "2015-02-03 02:12:36", updated_at: "2015-02-03 02:12:36">,
  4. #<Client id: 2, name: "yan", gender: "1", created_at: "2015-02-03 02:48:11", updated_at: "2015-02-03 02:48:11">]>

  1. clients = Client.includes(:address).limit(2)
  2.  
  3. clients.each do |client|
  4. puts client.address.postcode
  5. end

生成的sql语句为:

  1. Client Load (0.5ms) SELECT "clients".* FROM "clients" LIMIT 2
  2. Address Load (0.4ms) SELECT "addresses".* FROM "addresses" WHERE "addresses"."client_id" IN (1, 2)
  3. => #<ActiveRecord::Relation [#<Client id: 1, name: "wei", gender: "1", created_at: "2015-02-03 02:12:36", updated_at: "2015-02-03 02:12:36">,
  4. #<Client id: 2, name: "yan", gender: "1", created_at: "2015-02-03 02:48:11", updated_at: "2015-02-03 02:48:11">]>

按需加载多个关联

  1. clients = Client.all
  2. clients.each do |client|
  3. puts client.address.infos.first.history
  4. end

生成的sql语句:

  1. Address Load (0.3ms) SELECT "addresses".* FROM "addresses" WHERE "addresses"."client_id" = ? LIMIT 1 [["client_id", 1]]
  2. Info Load (0.3ms) SELECT "infos".* FROM "infos" WHERE "infos"."address_id" = ? ORDER BY "infos"."id" ASC LIMIT 1 [["address_id", 1]]
  3. 1110
  4. Address Load (0.1ms) SELECT "addresses".* FROM "addresses" WHERE "addresses"."client_id" = ? LIMIT 1 [["client_id", 2]]
  5. Info Load (0.1ms) SELECT "infos".* FROM "infos" WHERE "infos"."address_id" = ? ORDER BY "infos"."id" ASC LIMIT 1 [["address_id", 2]]
  6. 2110
  7. => [#<Client id: 1, name: "wei", gender: "1", created_at: "2015-02-03 02:12:36", updated_at: "2015-02-03 02:12:36">, #<Client id: 2, name: "yan", gender: "1", created_at: "2015-02-03 02:48:11", updated_at: "2015-02-03 02:48:11">]

Client和Address是has_one关系, Address和info是has_many关系, 想要一次性加载资源使client可以通过address获取info, 使用下面语句:

  1. clients = Client.includes(address: :infos)

生成的sql语句:

  1. Client Load (0.4ms) SELECT "clients".* FROM "clients"
  2. Address Load (0.5ms) SELECT "addresses".* FROM "addresses" WHERE "addresses"."client_id" IN (1, 2)
  3. Info Load (0.3ms) SELECT "infos".* FROM "infos" WHERE "infos"."address_id" IN (1, 2)
  4. => #<ActiveRecord::Relation [#<Client id: 1, name: "wei", gender: "1", created_at: "2015-02-03 02:12:36", updated_at: "2015-02-03 02:12:36">, #<Client id: 2, name: "yan", gender: "1", created_at: "2015-02-03 02:48:11", updated_at: "2015-02-03 02:48:11">]>

  

  1. clients.each do |c|
  2. puts c.address.infos.first.history
  3. end

输出:

1110
2110

rails数据库查询 N + 1 查询的解决办法的更多相关文章

  1. mysql数据库死锁的产生原因及解决办法

    这篇文章主要介绍了mysql数据库锁的产生原因及解决办法,需要的朋友可以参考下   数据库和操作系统一样,是一个多用户使用的共享资源.当多个用户并发地存取数据 时,在数据库中就会产生多个事务同时存取同 ...

  2. access数据库select查询top时无效的解决办法

    access数据库select查询top时有时无效,原因就是在使用Order by时,且排序的条件中数据有重复的. 比如:select top 10 * from table1 order by cd ...

  3. hive命令查询数据不显示表头解决办法

    在hive命令行中查询数据如下: 表头未显示出来 解决办法: 修改hive安装包conf/hive-site.xml配置文件: <property> <name>hive.cl ...

  4. SQL SERVER 数据库被标记为“可疑”的解决办法

    问题背景: 日常对Sql Server 2005关系数据库进行操作时,有时对数据库(如:Sharepoint网站配置数据库名Sharepoint_Config)进行些不正常操作如数据库在读写时而无故停 ...

  5. python 数据库操作产生中文乱码的解决办法

    1.执行python mysql数据库查询操作时,产生中文乱码 #!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb db = MySQLd ...

  6. L SERVER 数据库被标记为“可疑”的解决办法

    问题背景: 日常对Sql Server 2005关系数据库进行操作时,有时对数据库(如:Sharepoint网站配置数据库名Sharepoint_Config)进行些不正常操作如数据库在读写时而无故停 ...

  7. SQLite数据库在多线程写锁文件的解决办法

    参考了很多SQLITE数据库多线程的解决办法 我自己写了一个SQLITEHELPER 来解决这个问题 希望大家多多指教 调用的时候  SQLLiteDBHelper _SQLLiteDBHelper ...

  8. Sql Server 2008 数据库附加失败提示9004错误解决办法

    附加数据库 对于 服务器“WSS_Content”失败.  (Microsoft.SqlServer.Smo)执行 Transact-SQL 语句或批处理时发生了异常. (Microsoft.SqlS ...

  9. sql server 数据库正在使用该文件的解决办法

    今天在帮朋友还原数据库时遇到了一个问题.朋友用的是sql server 2008数据库,本身有一个数据库,他在修改程序的时候,想修改数据库的内容.但是又不想在原数据库中修改.想备份还原出一个数据库然后 ...

  10. 远程连接mysql数据库提示:ERROR 1130的解决办法

    From: http://blog.sina.com.cn/s/blog_716844910100welz.html 在linux下使用mysql客户端连接远程mysql服务器报错: [root@Se ...

随机推荐

  1. HDOJ 1009. Fat Mouse' Trade 贪心 结构体排序

    FatMouse' Trade Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  2. java.lang.String.getBytes(String charsetName)方法实例

    java.lang.String.getBytes(String charsetName) 方法编码将此String使用指定的字符集的字节序列,并将结果存储到一个新的字节数组. 声明 以下是java. ...

  3. 一枚招聘信息——分期乐招页面重构/UI开发(8k-12k 深圳 经验1-3年 学历不限 全职)

    腾讯人创建的分期乐公司,急需页面重构人才若干枚,公司前景好,机会难得,有兴趣的速速 8k-12k 深圳 经验1-3年 学历不限 全职 公司网站: http://www.fenqile.com/ 职位诱 ...

  4. Salesforce Apex 开发环境设置和Hello World示例

    本文介绍了Salesforce Apex开发环境的设置以及一个简单的Hello World示例的实现过程. Salesforce开发环境 Salesforce通过http://developer.fo ...

  5. [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二

    Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...

  6. [LeetCode] Search a 2D Matrix II 搜索一个二维矩阵之二

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  7. [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树

    Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  8. C#进阶系列——一步一步封装自己的HtmlHelper组件:BootstrapHelper(三:附源码)

    前言:之前的两篇封装了一些基础的表单组件,这篇继续来封装几个基于bootstrap的其他组件.和上篇不同的是,这篇的有几个组件需要某些js文件的支持. 本文原创地址:http://www.cnblog ...

  9. 跨域请求——WebClient通过get和post请求api

    AJAX不可以实现跨域请求,经过特殊处理才行.一般后台可以通过WebClient实现跨域请求~ //get 请求        string url = string.Format("htt ...

  10. Nginx配置Https

    1.申请证书: https://console.qcloud.com/ssl?utm_source=yingyongbao&utm_medium=ssl&utm_campaign=qc ...