我正在尝试在postgresql中运行以下操作:
/v1.25/networks?filters=%7B%22name%22%3A%7B%22MyNetwork%22%3Atrue%7D%7D"
他们都是独立工作的,这是:
FOR realm_id IN (SELECT id from decision_realms WHERE id NOT IN (SELECT realm_id FROM voters WHERE realm_id IS NOT NULL))
LOOP
INSERT INTO voters (voter_user_id, max_weight, actual_weight)
SELECT contributor_user_id, pps, pps
FROM contributors WHERE
project_id= (SELECT project_id FROM goals WHERE id=(SELECT goal_id FROM decision_realms WHERE id=realm_id))
END LOOP;
返回一列ids,
(SELECT id from decision_realms WHERE id NOT IN (SELECT realm_id FROM voters WHERE realm_id IS NOT NULL))
当realm_id被硬编码为值(1)时,按预期填充选民表。
但是如果我尝试替换值1,并根据select的结果使用变量和循环,则for循环不起作用。它说有语法错误。
这可以在不使用FOR LOOP的情况下完成吗?或者我该怎么写呢?
答案 0 :(得分:1)
您没有显示语法错误,但我想问题是您的PL / pgSQL变量与您在查询中使用的列具有相同的名称。
具体来说,循环变量是realm_id
,它也是表voters
中列的名称。
解决方案是为变量使用不同的名称。
答案 1 :(得分:1)
不优雅且未经过测试(可能有错误),但应该是那样
INSERT INTO voters (voter_user_id, max_weight, actual_weight)
SELECT contributor_user_id, pps, pps
from
(
SELECT contributor_user_id, pps, pps
FROM contributors WHERE
project_id in (
(SELECT project_id FROM goals WHERE id in (SELECT goal_id FROM decision_realms
WHERE id in (SELECT id from decision_realms WHERE id NOT IN (SELECT realm_id FROM voters WHERE realm_id IS NOT NULL))
))
)dec_realms
或使用with
声明
with dec_realms as
(
SELECT contributor_user_id, pps, pps
FROM contributors WHERE
project_id in (
SELECT project_id FROM goals WHERE id in (SELECT goal_id FROM decision_realms
WHERE id in (SELECT id from decision_realms WHERE id NOT IN (SELECT realm_id FROM voters WHERE realm_id IS NOT NULL))
))
)
INSERT INTO voters (voter_user_id, max_weight, actual_weight)
SELECT contributor_user_id, pps, pps
from dec_realms;
其他选项是使用控件结构FOR
,就像那样
DO
$$
DECLARE
_id integer;
BEGIN
FOR _id IN (SELECT id from decision_realms WHERE id NOT IN (SELECT realm_id FROM voters WHERE realm_id IS NOT NULL))
LOOP
INSERT INTO voters (voter_user_id, max_weight, actual_weight)
SELECT contributor_user_id, pps, pps
FROM contributors WHERE
project_id= (SELECT project_id FROM goals WHERE id=(SELECT goal_id FROM decision_realms WHERE id=_id));
END LOOP;
END
$$
我知道如果我犯了错误,我确实缺乏表格结构。第一个和第二个选项可能更快,因为1次操作而不是单独执行每个插入。
答案 2 :(得分:0)
这是有效的。可能它必须是一个脚本而不仅仅是一个声明......或类似的东西。
<?php
class Users extends CI_Model {
public function getUsers() {
$this->load->database();
$data = "yes"; //here you can write query to get data from table see query builder in codeigniter
return $data; //here you have to return data
}
}