有什么方法可以让我在 SELECT 子句中使用一个带有子查询的选择散列,以便在 SqlUtil::AbstractTable 上使用方法(如 getRowIterator())。
我在 select_option_superquery 中发现了类似的东西但是在那里使用的子查询可以在 FROM 子句中找到:
SELECT serviceid, service_methodid FROM (SELECT serviceid,service_methodid..)...
当我在寻找类似的东西时:
SELECT t1.id, t1.order_id,
(SELECT COUNT(order_id) FROM tbl1 t2 WHERE t1.order_id = t2.order_id) as count,
t1.other_cols,
t3.other_cols
FROM tbl1 t1 left join tbl3 s on t1.id = t3.id
期望的结果是在结果集中计数
order_id
tbl1
id order_id other_cols
1 ord1 ...
2 ord2 ...
3 ord1 ...
结果:
id order_id count other_cols
1 ord1 2 ...
2 ord2 1 ...
3 ord1 2 ...
最佳答案
您不能完全按照您的意愿执行此操作(使用子查询作为选择列),但您可以使用 superquery 执行此操作。您提到的选项,并通过使用 SQL 窗口函数与 SqlUtil 和 cop_over() function
代码可能如下所示:
list cols = (
"id",
"order_id",
cop_as(cop_over(cop_count("order_id"), "order_id"), "count"),
# ... other columns to select here - this is in the inner query
);
hash sh = (
"columns": cols,
"join": join_inner(t2, "t2", ("order_id": "order_id")) +
join_inner(t3, "t3", ("id": "id")),
"superquery": (
"columns": (
cop_distinct("id"), "order_id", "count"
# note put columns needed here without table prefixes, this is for the outer query
),
),
);
SqlUtil 的子查询有点违反直觉,子查询使用顶级哈希参数指定,然后主查询(从子查询中选择)使用 super 查询哈希键指定,如上例所示。请注意,这将生成一个查询,其中
t2
中必须至少有一行。 .如果行在
t2
是可选的,使用 join_left()
而不是 join_inner()
.以下代码将执行上面的查询哈希并记录生成的 SQL 和结果:
string sql;
list l = t1.selectRows(sh, \sql);
log(LL_INFO, "sql: %s", sql);
log(LL_INFO, "SQL results: %N", l);
我希望这有帮助!
关于sql - Qorus 嵌套选择哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41503112/