Applying CTE for recursive queries

走远了吗. 提交于 2019-12-05 10:46:22

Please comment whether these should be done differently, or from a performance perspective, whether they have any major issues?

Objective #1

MariaDB [recursion]> WITH RECURSIVE t AS (
    ->     SELECT accounts_id FROM holdings WHERE active=0
    ->     UNION ALL
    ->     SELECT pha.portfolios_id
    ->     FROM portfolios_has_accounts pha
    ->     INNER JOIN t ON t.accounts_id=pha.accounts_id
    -> )
    -> SELECT a.* FROM accounts a
    -> LEFT OUTER JOIN t ON t.accounts_id=a.id
    -> WHERE t.accounts_id IS NULL;
+----+------------+-----------+
| id | name       | type      |
+----+------------+-----------+
| h1 | holding1   | holding   |
| h3 | holding3   | holding   |
| h4 | holding4   | holding   |
| p3 | portfolio3 | portfolio |
+----+------------+-----------+
4 rows in set (0.00 sec)

Objective #2

MariaDB [recursion]> WITH RECURSIVE t AS (
    -> SELECT pha.*, h.value
    -> FROM portfolios_has_accounts pha
    -> LEFT OUTER JOIN holdings h ON h.accounts_id=pha.accounts_id
    -> WHERE pha.portfolios_id="p1"
    -> UNION ALL
    -> SELECT pha.portfolios_id, pha.accounts_id, pha.weight*t.weight, h.value
    -> FROM t
    -> INNER JOIN portfolios_has_accounts pha ON pha.portfolios_id=t.accounts_id
    -> LEFT OUTER JOIN holdings h ON h.accounts_id=pha.accounts_id
    -> )
    -> SELECT SUM(weight*value) FROM t WHERE value IS NOT NULL;
+-------------------+
| SUM(weight*value) |
+-------------------+
| 170.0000          |
+-------------------+
1 row in set (0.00 sec)

Objective #3

MariaDB [recursion]> WITH RECURSIVE t AS (
    -> SELECT pha.*, h.value
    -> FROM portfolios_has_accounts pha
    -> LEFT OUTER JOIN holdings h ON h.accounts_id=pha.accounts_id
    -> WHERE pha.portfolios_id="p1"
    -> UNION ALL
    -> SELECT pha.portfolios_id, pha.accounts_id, pha.weight*t.weight, h.value
    -> FROM t
    -> INNER JOIN portfolios_has_accounts pha ON pha.portfolios_id=t.accounts_id
    -> LEFT OUTER JOIN holdings h ON h.accounts_id=pha.accounts_id
    -> )
    -> SELECT accounts_id, weight FROM t WHERE value IS NOT NULL;
+-------------+--------+
| accounts_id | weight |
+-------------+--------+
| h1          | 1.00   |
| h2          | 1.00   |
| h3          | 1.00   |
| h4          | 0.25   |
+-------------+--------+
4 rows in set (0.01 sec)

MariaDB [recursion]>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!