2

我想选择items属于一个产品。它们必须在items.condition. 这是查询:

SELECT DISTINCT ON (items.condition) items.id, items.condition, items.price, products.name
FROM products
INNER JOIN items ON products.id = items.product_id
WHERE products.id = 1
ORDER BY items.condition, items.price, products.name;

我试过这个,但我得到了StatementInvalid错误。我正在使用 Rails 4。

product = Product.find(1)
product.items.select("DISTINCT ON(items.condition) items.id, products.*, items.*").order('items.condition, items.price, products.name')

错误:

PG::Error: ERROR:  missing FROM-clause entry for table "products"
LINE 1: SELECT DISTINCT ON(items.condition) items.id, products.*, it...
                                                      ^
: SELECT DISTINCT ON(items.condition) items.id, products.*, items.* FROM "items"  WHERE "items"."product_id" = $1  ORDER BY items.condition, items.price, products.name
ActiveRecord::StatementInvalid: PG::Error: ERROR:  missing FROM-clause entry for table "products"
LINE 1: SELECT DISTINCT ON(items.condition) items.id, products.*, it...
4

1 回答 1

2

试试这个(未测试)

Product.joins(:items).select("DISTINCT(items.condition), items.id, products.*").order('items.condition, items.price, products.name')
于 2013-07-08T15:47:15.570 回答