![](/img/trans.png)
[英]Insert column data rows (all) in another column table where each row matches the common ID
[英]Select rows from a filtered portion of Table A where a column matches a relationship with a column from the row in Table B that matches by ID
我想获取表中的所有行,其中一列与另一个表中具有相同另一列值的行中列的值的值的关系匹配。
具体来说,我有两个表,我通过Amazon Redshift访问的订单和product_info
命令
| ID | Date | Amount | Region |
=====================================
| 1 | 2019/4/1 | $120 | A |
| 1 | 2019/4/4 | $100 | A |
| 2 | 2019/4/2 | $50 | A |
| 3 | 2019/4/6 | $70 | B |
订单的分区键是区域和日期。
产品信息
| ID | Release Date | Region |
| ---- | ------------ | ------ |
| 1 | 2019/4/2 | A |
| 2 | 2019/4/3 | A |
| 3 | 2019/4/5 | B |
产品信息的主键是id,分区键是区域。
我想从区域A中的订单获取所有行,其中行的日期大于该ID的产品信息中的发布日期值。
所以在这种情况下它应该只返回一行,
| 1 | 2019/4/4 | $100 | A |
我试过了
select *
from orders
INNER JOIN product_info ON orders.date>product_info.release_date
AND orders.id=product_info.id
AND orders.region=A
AND product_info.region=A
limit 10
问题是这个查询非常缓慢(10分钟后取消)。 这些表非常大,我感觉它是扫描整个表而不是首先将它限制为区域(实际上除了我要在内部连接之前应用于ID列表的区域之外还有其他过滤器,但为了简化问题,我只限于区域)。
我怎样才能有效地编写这种类型的查询?
使SQL查询更快的最佳方法是尽快排除行。
因此,不要在JOIN语句中添加类似orders.region=A
条件,而应将它们移到WHERE
语句中。 这将在连接之前消除行。
此外,使JOIN
条件尽可能简单,以便数据库可以优化比较。
尝试这样的事情:
SELECT *
FROM orders
INNER JOIN product_info ON orders.id = product_info.id
WHERE orders.region = 'A'
AND product_info.region = 'A'
AND orders.date > product_info.release_date
任何进一步的优化都需要考虑Redshift表上的DISTKEY
和SORTKEY
。 (最好是id
的DISTKEY
和date
的SORTKEY
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.