简体   繁体   English

Ruby on Rails转换为SQL查询

[英]Ruby on rails convert to sql query

I have did the first one, and want to check if I got it right or not? 我做了第一个,想检查我是否正确? also I have no idea how to do number 2 Ruby ORM Consider the following two active record definitions over the tables “customers” and “orders”. 我也不知道该怎么做2 Ruby ORM考虑在表“ customers”和“ orders”上的以下两个活动记录定义。 The orders table has a foreign key “cust_key” that references the primary key of “customers”, which is also named “cust_key”. 订单表具有一个外键“ cust_key”,该外键引用了“客户”的主键,也称为“ cust_key”。

Table:
customers-
          cust_key
          address

orders-
          order key
          cust_key
          order_priority
          total_price

1 class Customer < ActiveRecord::Base
2 set_table_name "customers"
3 set_primary_key "cust_key"
4 has_many :orders, :foreign_key => "cust_key”
5 End

1 class Order < ActiveRecord::Base
2 set_table_name "orders"
3 belongs_to :customer, :foreign_key => "cust_key"
4 set_primary_key "order_key”
5 end

Consider the following piece of Ruby-on-Rails code.
1 <table>
2 <% Customers.all.each.do |c| %>
3 <tr>
4 <td><%= c.address %></td>
5 <td><%= c.orders.count() %></td>
6 </tr>
7 <% end %>
8 </table>

Questions: 问题:

  1. Provide the SQL queries that will result from executing this piece of Ruby-on-Rails. 提供执行此Ruby-on-Rails所产生的SQL查询。 How many SQL queries in total will be executed? 总共将执行多少个SQL查询?

2 queries 2查询
SELECT address FROM customers 选择客户的地址

     SELECT COUNT(*) FROM orders where orders.cust_key= customers.cust_key;
  1. Write a jsp fragment that issues only one SQL query and creates identical html with the Ruby-on-Rails fragment above. 编写一个仅发出一个SQL查询的jsp片段,并与上面的Ruby-on-Rails片段创建相同的html。

I know that this is an old question, and you've probably forgotten it but ... If you change: 我知道这是一个古老的问题,您可能已经忘记了,但是...如果您进行更改:

<% Customers.all.each.do |c| %>
  <tr>
    <td><%= c.address %></td>
    <td><%= c.orders.count() %></td>
  </tr>
<% end %>

to

<% Customers.includes(:orders).each.do |c| %>
  <tr>
    <td><%= c.address %></td>
    <td><%= c.orders.length %></td>
  </tr>
<% end %>

You'll display the customer information in one SQL call. 您将在一个SQL调用中显示客户信息。

The includes method, changes the request so that it uses a single query with a join, to gather all customers with their corresponding order records include方法更改请求,以便它使用带有联接的单个查询来收集所有客户及其相应的订单记录

Note that I've used length rather than count, as count will call a SQL count for each customer (c) object, whereas length will look at the length of orders data already gathered in the first SQL call. 请注意,我使用了长度而不是计数,因为count将为每个客户(c)对象调用一个SQL计数,而length将查看在第一个SQL调用中已经收集的订单数据的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM