在子查询中使用限制

时间:2012-10-03 04:33:49

标签: mysql

我有4张桌子

  • 产品
  • 状态
  • 订单
  • orders_products。

使用以下查询我得到了正确的结果,但它的顺序不正确,即结果通过子查询得到。我想将结果顺序作为子查询结果。

SELECT 
    p.products_id, p.products_image, p.products_tax_class_id,
    pd.products_name, if(s.status, s.specials_new_products_price,
    p.products_price) as products_price 
FROM
    products p LEFT JOIN specials s
        ON p.products_id = s.products_id, products_description pd 
WHERE
    p.products_status = '1' 
    AND p.products_id = pd.products_id 
    AND pd.language_id = '2' 
    AND p.products_id in (
        SELECT * from (
            SELECT
                distinct(op.products_id) 
            FROM
                orders_products op,orders o 
            WHERE
                op.orders_id=o.orders_id 
                AND o.customers_id='27' 
            ORDER BY
                o.date_purchased 
            DESC LIMIT 0,10 
        ) AS temptable
    )

1 个答案:

答案 0 :(得分:0)

外部SELECT有一个ORDER BY pd.products_name。那是应该适用的,只有那样。

子查询ORDER BY实际上并不重要。你应该得到相同的结果删除它。

如果您想要从pd.products_name获得不同的排序顺序,则必须按顺序排序所需的列。在您的情况下,您需要将orders.date_purchased移动到查询的主要部分,以便您可以使用它进行排序。反转查询,即从您想要的内容开始并与其他所有相关:

    SELECT MAX(o.date_purchased) AS date_purchased, DISTINCT (op.products_id) AS products_id
    p.products_id, p.products_image, p.products_tax_class_id, p.products_price
    pd.products_name,
    IF (s.status, s.specials_new_product_price, p.products_price) AS products_price

    FROM orders o

    LEFT JOIN orders_products op USING (orders_id)
    LEFT JOIN products p USING (products_id)
    LEFT JOIN products_description pd USING (products_id)
    LEFT JOIN specials s USING (products_id)
    WHERE o.customers_id = '27'
    AND p.products_status = 1
    AND pd.language_id = 2