2

我正在开发一个民意调查应用程序。SQL 模式是:

polls -> * options (poll_id) -> * answers (option_id)

或者:“投票有很多选项,选项可以有答案(又名投票)”

每次投票我只能允许每个用户投一票。这是合并子句(显然不起作用):

  merge into answers
  using (select count(*)
         from answers, options, polls
         where answers.option_id = options.id
         and options.poll_id = polls.id
         and polls.id = {poll_id}
         and answers.owner_id = {owner_id}) votes
  on (votes = 0)
  when matched then
  insert into answers values (NULL, {option_id}, {owner_id}, NOW())
4

2 回答 2

1

如果您从不想更新,那么应该做一个简单的插入。我根本不认为需要合并:

insert into answers (some_value, option_id, owner_id, last_modified)
select null, {option_id}, {owner_id}, current_timestamp
from dual
where not exists (select 1 
                  from answers a
                    join options o on o.id = a.option_id
                    join polls p on p.id = o.poll_id
                  where a.owner_id = {owner_id}
                    and p.id = {polls_id}

我明确列出了插入子句的列,因为不这样做是不好的编码风格。我当然只是猜到了你的列名,因为你没有向我们展示你的表定义。

于 2012-07-16T21:59:26.337 回答
0

尝试这个:

MERGE INTO answers
USING 
(SELECT options.id 
             FROM options, polls
             WHERE options.poll_id = polls.id
             AND polls.id = {poll_id}
) options
ON (answers.option_id = options.id AND answers.owner_id = {owner_id})
WHEN NOT MATCHED THEN
    INSERT INTO answers VALUES (NULL, {option_id}, {owner_id}, SYSDATE)
WHEN MATCHED THEN
    -- Do what you need to do for an update
于 2012-07-16T21:59:51.907 回答