Sqlite 3 插入和替换在 1 个以上的唯一列上失败 [英] Sqlite 3 Insert and Replace fails on more than 1 unique column
问题描述
我正在使用一个表来存储不同用户在不同民意调查中的投票.
I am using a table to store votes of different users on different polls.
表具有以下结构.
id | poll_id | opt | ip_address
id : auto increment
poll_id : (STRING UNIQUE) unique for a particular poll
opt : (STRING) option selected by user
ip_address: (STRING UNIQUE) ip address of user
这是我的查询
INSERT OR REPLACE INTO tbl_poll(id,poll_id,opt,ip_addr) VALUES (null,'$poll_id','$opt','$ip_addr')
(这里 $poll_id、$opt 和 $ip_addr 是保存各自值的 php 变量)
现在的场景是这样的,
用户A"投票支持 poll_id 'mypoll' 的选项 2.查询工作完美.(是否插入)
User 'A' votes for option 2 of poll_id 'mypoll'. Query works perfectly. (Does insert)
用户A"改变主意并投票支持 poll_id 'mypoll' 的选项 5.查询工作完美.(确实替换)
User 'A' changes mind and votes for option 5 of poll_id 'mypoll'. Query works perfectly. (Does replace)
但是如果用户A"投票支持 poll_id 'yourpoll' 的选项 4.查询失败(它进行了替换)但它应该插入一个带有 poll_id 'yourpoll' 的新记录
But if User 'A' votes for option 4 of poll_id 'yourpoll'. Query fails (It does a replace) but it should insert a new record with poll_id 'yourpoll'
我认为,它只考虑了 ip_address
的 unqiue
约束,而不考虑 poll_id
I think, it considers the unqiue
constraint of ip_address
only but not the poll_id
推荐答案
从您对所需功能的描述来看,您似乎希望 poll_id
和 ip_address
一个唯一的对或唯一的复合.
From your description on the desired functionality, it would seem that you want poll_id
and ip_address
to be a unique pair or compound unique.
CREATE TABLE tbl_poll (
id INTEGER PRIMARY KEY AUTOINCREMENT,
poll_id STRING NOT NULL,
ip_address STRING NOT NULL,
opt STRING NULL,
CONSTRAINT 'unique_vote_per_poll_per_ip_address' UNIQUE ( poll_id, ip_address ) ON CONFLICT REPLACE
);
这篇关于Sqlite 3 插入和替换在 1 个以上的唯一列上失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!