admin管理员组文章数量:1328003
I have 2 SQLite tables, users
and transactions
where a "transaction" happens between exactly 2 users.
A short example would be:
CREATE TABLE users(
id INTEGER PRIMARY KEY ASC
);
CREATE TABLE transactions(
id INTEGER PRIMARY KEY ASC
participant_1_id INTEGER REFERENCES users,
participant_2_id INTEGER REFERENCES users,
);
Now, I want to enforce that participant_1_id
and participant_2_id
must be different because a user cannot make a transaction with themselves.
However everything I find on both SO and Google is only about making a pair of columns UNIQUE
, which is of no use to me since user 1
and user 2
may perform multiple transactions between themselves, so the pair of (userId1, userId2)
will 100% show up more than once in transactions
.
Is there a way to enforce 2 columns to be different?
I have 2 SQLite tables, users
and transactions
where a "transaction" happens between exactly 2 users.
A short example would be:
CREATE TABLE users(
id INTEGER PRIMARY KEY ASC
);
CREATE TABLE transactions(
id INTEGER PRIMARY KEY ASC
participant_1_id INTEGER REFERENCES users,
participant_2_id INTEGER REFERENCES users,
);
Now, I want to enforce that participant_1_id
and participant_2_id
must be different because a user cannot make a transaction with themselves.
However everything I find on both SO and Google is only about making a pair of columns UNIQUE
, which is of no use to me since user 1
and user 2
may perform multiple transactions between themselves, so the pair of (userId1, userId2)
will 100% show up more than once in transactions
.
Is there a way to enforce 2 columns to be different?
Share Improve this question edited Feb 10 at 19:54 Zegarek 26.7k5 gold badges24 silver badges30 bronze badges asked Dec 3, 2024 at 23:17 Rares DimaRares Dima 1,7691 gold badge19 silver badges45 bronze badges 1 |1 Answer
Reset to default 6You can implement CHECK constraints on the columns.
Fiddle
CREATE TABLE users (
id INTEGER PRIMARY KEY ASC
);
CREATE TABLE transactions (
id INTEGER PRIMARY KEY ASC,
participant_1_id INTEGER REFERENCES users(id),
participant_2_id INTEGER REFERENCES users(id),
CHECK (participant_1_id != participant_2_id)
);
This succeeds
INSERT INTO transactions (participant_1_id, participant_2_id) VALUES (1, 2);
This fails
INSERT INTO transactions (participant_1_id, participant_2_id) VALUES (1, 1);
本文标签: sqlSQLite constraint for making 2 columns differentStack Overflow
版权声明:本文标题:sql - SQLite constraint for making 2 columns different - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742245677a2439319.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
CHECK
constraint? Something likeCHECK(userId1 <> userId2)
. See sqlitetutorial/sqlite-check-constraint – PM 77-1 Commented Dec 3, 2024 at 23:33