1

我正在使用 Mysql 5.1,并且有这个查询,有没有办法不使用子查询并完成相同的结果?

SELECT oref.affiliate_id, ROUND(sum( oph.amount ) * 0.10 ,2) AS tsum
FROM operators_referer AS oref 
LEFT JOIN operators_payments_history AS oph 
ON oref.operator_id = oph.operator_id
WHERE oref.affiliate_id = 28221
AND
(
    oph.date_paid > 
    (
        SELECT MAX(aph.date_paid) 
        FROM affiliates_payments_history AS aph 
        WHERE aph.operator_id = oref.affiliate_id
    )
    OR 
    (
        SELECT MAX(aph.date_paid)
        FROM affiliates_payments_history AS aph 
        WHERE aph.operator_id = oref.affiliate_id 
    ) 
    is NULL
)
4

5 回答 5

3

不要这样做! 如果表的索引正确,并且数据库结构合理,那么几乎肯定最好将其保留为子查询。根据您的评论,这似乎会简化和加快速度 - 但不一定如此。解析器不一定会更好地处理非子查询表单。子查询的清晰性,以及重写为不使用子查询的查询的复杂性,认为这不是一个值得的目标。

你需要知道它是否可以完成?它可以:对此CS.stackexchange 问题 的回答显示了如何做到这一点,并且有人指出,没有办法让子查询不能写为基于连接的查询,并且没有可能的集合差异。这意味着有一种方法可以简化它,并且一些指向算法方法的链接被链接到。

于 2012-06-25T15:33:02.247 回答
2

你试过一个HAVING子句吗?

SELECT oref.affiliate_id, ROUND(sum( oph.amount ) * 0.10 ,2) AS tsum
FROM operators_referer AS oref 
LEFT JOIN operators_payments_history AS oph 
ON oref.operator_id = oph.operator_id
LEFT JOIN affiliates_payments_history AS aph
ON aph.operator_id = oref.affiliate_id
WHERE oref.affiliate_id = 28221
GROUP BY oref.affiliate_id
HAVING MAX(aph.date_paid) > oph.date_paid OR MAX(aph.date_paid) IS NULL
于 2012-06-25T14:49:18.360 回答
1

试试这个::

  SELECT oref.affiliate_id, ROUND(sum( oph.amount ) * 0.10 ,2) AS tsum
    FROM operators_referer AS oref 
    LEFT JOIN operators_payments_history AS oph 
    ON oref.operator_id = oph.operator_id
   LEFT JOIN affiliates_payments_history AS aph ON aph.operator_id = oref.affiliate_id
    WHERE oref.affiliate_id = 28221
  GROUP BY oref.affiliate_id
  HAVING IFNULL(MAX(aph.date_paid),0 > oph.date_paid)
于 2012-06-25T14:45:24.873 回答
1
SELECT MAX(aph.date_paid) AS max_aph, 
       oref.affiliate_id, 
       ROUND(sum( oph.amount ) * 0.10 ,2) AS tsum
FROM operators_referer AS oref 
LEFT JOIN operators_payments_history AS oph 
       ON oref.operator_id = oph.operator_id
LEFT JOIN affiliates_payments_history AS aph 
       ON aph.operator_id = oref.affiliate_id
WHERE oref.affiliate_id = 28221
AND (oph.date_paid > max_aph OR max_aph is NULL)

没有尝试过,但我认为这就是您正在搜索的内容。

于 2012-06-25T14:48:41.057 回答
1

您正在寻找的是一个简单的JOIN逻辑。

像这样:

SELECT oref.affiliate_id, ROUND(sum( oph.amount ) * 0.10 ,2) AS tsum
FROM operators_referer AS oref 
     LEFT JOIN operators_payments_history AS oph 
            ON oref.operator_id = oph.operator_id
     LEFT JOIN affiliates_payments_history AS aph
            ON aph.operator_id = oref.affiliate_id
WHERE oref.affiliate_id = 28221
AND ( oph.date_paid > MAX(aph.date_paid)
OR MAX(aph.date_paid) IS NULL)    
GROUP BY oref.affiliate_id;

查询的意思基本上是“将 aph 和 oph 表加入 oref,仅在 oref.affiliate_id 范围内应用 max 函数,并查找条件适用的行”

在 MySQL 手册中了解更多关于JOIN和功能是明智的LEFT JOIN

于 2012-06-25T14:52:41.540 回答