MySQL选择复杂的子查询作为字段

时间:2013-09-11 14:53:59

标签: php mysql sql

我目前有:

SELECT tbl_review.*, users.first_name, users.last_name, (
    SELECT order_ns.tran_date 
    FROM order_ns 
    LEFT JOIN product_2_order_ns.external_order_id = order_ns.order_id 
    WHERE product_2_order_ns.bkfno IN :id
    ORDER BY order_ns.trandate ASC 
    LIMIT 1
) as purchase_date
FROM tbl_review
LEFT JOIN users ON users.sequal_user_id = tbl_review.user_id
WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1

在其子查询中,选择用户拥有相关产品的订单(在:id中定义),获取其中一个找到订单的最早交易日期。

我真的希望将其保留在数据库的一次调用中(不是真的想为每个返回的用户再次调用一个字段,或者甚至对所有用户进行范围查询)但显然这个特定的查询不是工作。

如果能够做到这一点,我该怎么办?

我无法将子查询转换为连接,因为它们是两个不同的数据,子查询需要返回主查询中每一行的详细信息。

2 个答案:

答案 0 :(得分:1)

我认为你只想要一个相关的子查询。目前尚不清楚内部查询与外部查询之间的关系究竟是什么。我的猜测是用户和订单:

SELECT tbl_review.*, users.first_name, users.last_name,
       (SELECT order_ns.tran_date 
        FROM order_ns LEFT JOIN
             product_2_order_ns
             on product_2_order_ns.external_order_id = order_ns.order_id and
                product_2_order_ns.bkfno = tbl_review.product_id and
        WHERE order_ns.user_id = tbl_review.user_id
        ORDER BY order_ns.trandate ASC 
        LIMIT 1
       ) as purchase_date
FROM tbl_review LEFT JOIN
     users
     ON users.sequal_user_id = tbl_review.user_id
WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1;

编辑:

哦,内部查询 与外部查询无关。然后它更容易。使用from

将其移至cross join子句
SELECT tbl_review.*, users.first_name, users.last_name,
       innerquery.tran_date as purchase_date
FROM tbl_review LEFT JOIN
     users
     ON users.sequal_user_id = tbl_review.user_id cross join
     (SELECT order_ns.tran_date 
      FROM order_ns LEFT JOIN
           product_2_order_ns
           on product_2_order_ns.external_order_id = order_ns.order_id 
      WHERE product_2_order_ns.bkfno IN :id
      ORDER BY order_ns.trandate ASC 
      LIMIT 1
     ) innerquery
WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1;

答案 1 :(得分:0)

@Gordons答案非常接近,但即使没有找到tran_date的数据,我希望它返回,所以我将查询更改为:

SELECT tbl_review.*, users.first_name, users.last_name, order_ns.tran_date
FROM tbl_review
LEFT JOIN users ON users.sequal_user_id = tbl_review.user_id 
LEFT JOIN order_ns ON order_ns.order_id = (
    SELECT order_ns.order_id 
    FROM order_ns
    LEFT JOIN product_2_order_ns on product_2_order_ns.external_order_id = order_ns.order_id
            WHERE product_2_order_ns.bkfno IN :id
    ORDER BY order_ns.tran_date ASC
    LIMIT 1
 ) 
 WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1;    

这将返回tran_date的不同数据,无论是否找到它。