如何简化针对Oracle DB的查询?

时间:2018-11-01 19:15:02

标签: sql oracle

202

我有两个订单表,OrderA和OrderB。我想编写一个查询,将用户的订单金额汇总为OrderA订单,但如果同一用户在同一个月内放置OrderB,则仅包括OrderA条目。

对于此示例数据,查询应提供distinct

此查询有效,但是SELECT userId, SUM (a.amount) FROM ( SELECT DISTINCT a.userId, a.amount FROM OrderA a INNER JOIN OrderB b ON EXTRACT(month from a.orderDate) = EXTRACT(month from b.orderDate) AND EXTRACT(year from a.orderDate) = EXTRACT(year from b.orderDate) AND a.userId = b.userId ) GROUP BY userId 速度很慢。

301

此查询不起作用,它给出SELECT userId, SUM (a.amount) FROM OrderA a INNER JOIN OrderB b ON EXTRACT(month from a.orderDate) = EXTRACT(month from b.orderDate) AND EXTRACT(year from a.orderDate) = EXTRACT(year from b.orderDate) AND a.userId = b.userId GROUP BY userId

<html>
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script>
function plotLine(array){
    var object1 =
    {
        "data":
        [{
            "x": array.map(i => i[0]),
            "y": array.map(i => i[1])
        }]
    };
    return object1;
}
</script>
</head>
<body>
<div id="plot"></div>
<script src="plots.js"></script>
</body>
</html>

有什么建议吗?我觉得有一种更好的方法来实现此查询。

2 个答案:

答案 0 :(得分:2)

这是您想要的吗?

SELECT a.userId, SUM(a.amount) 
FROM OrderA a
WHERE EXISTS (SELECT 1
              FROM OrderB b  
              WHERE TO_CHAR(a.orderDate, 'YYYY-MM') = TO_CHAR(b.orderDate, 'YYYY-MM') AND
                    a.userId = b.userId   
            ) 
GROUP BY a.userId;

为了提高性能,您希望在OrderB(userId, orderDate)上建立索引。

答案 1 :(得分:1)

SELECT userId, SUM (a.amount) 
FROM (
            SELECT a.userId, a.amount
              FROM OrderA a
             INNER JOIN OrderB b  
            ON              EXTRACT(month from a.orderDate) = EXTRACT(month from b.orderDate) AND
                            EXTRACT(year from a.orderDate) = EXTRACT(year from b.orderDate) AND
                            a.userId = b.userId
             GROUP BY a.userId, a.amount
    )
GROUP BY userId;

在没有区别的情况下,使用相同的逻辑可能会更快。