one column value reference from two tables is it support SQLITE - sqlite

one column value reference from two tables is it support SQLITE
see the below table structure
account_id reference from two tables
FOREIGN KEY(account_id) REFERENCES account(id),
FOREIGN KEY(account_id) REFERENCES category(id)
CREATE TABLE transaction (
id NUMERIC PRIMARY KEY,
user_id NUMERIC NOT NULL,
account_id NUMERIC NOT NULL,
category_id NUMERIC NOT NULL,
amount DOUBLE NOT NULL, date VARCHAR(25) NOT NULL,
description VARCHAR(25),
FOREIGN KEY(account_id) REFERENCES account(id),
FOREIGN KEY(account_id) REFERENCES category(id)
);

This is possible.
All constraints must be met, i.e., each account_id value must appear in both parent tables.

Related

Sqlite foreign key mismatch?

I've read this question and understood the referenced foreign keys to be unique, but somehow the insertion to table are still throwing foreign key mismatch errors:
CREATE TABLE medication (
med_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
med_name VARCHAR (20) NOT NULL,
dosage VARCHAR (10)
);
CREATE TABLE disease (
dis_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
disease_name VARCHAR (20) NOT NULL
);
CREATE TABLE dis_med (
disease_id int NOT NULL,
medication_id int NOT NULL,
CONSTRAINT PK_dis_med PRIMARY KEY (disease_id, medication_id),
CONSTRAINT FK_dis FOREIGN KEY (disease_id) REFERENCES disease (dis_id),
CONSTRAINT FK_med FOREIGN KEY (medication_id) REFERENCES medication (med_id));
CREATE TABLE user_disease (
user_id REFERENCES user (user_id),
dis_id REFERENCES disease (dis_id),
med_id REFERENCES dis_med(medication_id),
CONSTRAINT PK_dis_user PRIMARY KEY (user_id, dis_id)
);
Through the list in the question I cited:
the parent table (medication, disease) exists.
the parent columns exist
the child table references all of the primary key columns in the parent table
Update1
I was able to insert data and bypass the error by altering the user_disease table by composite foreign key. I'd appreciate it if someone can point out what's the best design here. Many thanks in advance!
CREATE TABLE user_disease (
user_id REFERENCES user (user_id),
dis_id REFERENCES disease (dis_id),
med_id REFERENCES dis_med(medication_id),
CONSTRAINT FK_dis_med FOREIGN KEY REFERENCES dis_med(disease_id, medication_id),
CONSTRAINT PK_dis_user PRIMARY KEY (user_id, dis_id)
);
From SQLite Foreign Key Support/3. Required and Suggested Database Indexes:
Usually, the parent key of a foreign key constraint is the primary key of the parent table.
If they are not the primary key, then the parent key columns must be collectively
subject to a UNIQUE constraint or have a UNIQUE index.
With this:
CREATE TABLE user_disease (
...........................
med_id REFERENCES dis_med(medication_id),
...........................
);
the column med_id of user_disease references the column medication_id of dis_med, which is not the PRIMARY KEY of dis_med and there is no UNIQUE constraint for it. It just references med_id of medication .
Why do you need the column med_id in user_disease?
You have dis_id referencing disease, which may also be used to retrieve from dis_med (all) the row(s) from dis_med for that disease.

SQL Error Regarding Foreign Key Restraint

I am currently getting the following error when trying to add to one of my tables:
Error adding record: FOREIGN KEY constraint failed: (INSERT INTO Stock(StockID,ItemName,MinAmountRequired,AmountInStock,Order? (Yes/No),DataLastUpdated,OrderNumber,SupplierRefrence,PurchaseID`) VALUES (1,",0,0,",",0,0,0);)
Currently, This is how I have my tables set up:
Stock
CREATE TABLE Stock (
StockID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
ItemName TEXT NOT NULL,
MinAmountRequired INTEGER NOT NULL,
AmountInStock INTEGER NOT NULL,
Order? (Yes/No) TEXT NOT NULL,
DataLastUpdated TEXT NOT NULL,
OrderNumber INTEGER NOT NULL UNIQUE,
SupplierReference INTEGER NOT NULL,
PurchaseID INTEGER NOT NULL UNIQUE,
FOREIGN KEY(PurchaseID) REFERENCES Purchase(PurchaseID),
FOREIGN KEY(OrderNumber) REFERENCES Orders(OrderNumber),
FOREIGN KEY(SupplierReference) REFERENCES Supplier(SupplierReference));
Orders
CREATE TABLE Orders (
OrderNumber INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
CustomerReferenceNumber INTEGER NOT NULL UNIQUE,
OrderDate TEXT NOT NULL,
ItemName TEXT NOT NULL UNIQUE);
Suppliers
CREATE TABLE Supplier (
SupplierReference INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
Name TEXT NOT NULL UNIQUE,
Address TEXT NOT NULL UNIQUE,
ContactNumber INTEGER NOT NULL UNIQUE);
Purchases
CREATE TABLE Purchase (
PurchaseID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
Date TEXT NOT NULL,
AmountSpent REAL NOT NULL);
You have defined these foreign keys in table Stock:
FOREIGN KEY(PurchaseID) REFERENCES Purchase(PurchaseID),
FOREIGN KEY(OrderNumber) REFERENCES Orders(OrderNumber),
FOREIGN KEY(SupplierReference) REFERENCES Supplier(SupplierReference)
meaning that the values in columns PurchaseID, OrderNumber, SupplierReference need to reference values in columns of the tables Purchase, Orders and Supplier.
But you want to store 0 to all of these columns which I'm sure that is not the value of any of the referenced columns, since these referenced columns are defined as
PRIMARY KEY AUTOINCREMENT
and so their values are > 0.
Pass valid values that do exist in these 3 tables and the statement will execute succesfully.

Can not add a second foreign key when creating table

I am creating a table with 2 foreign keys
but whenever I have the second key, it will return an error:
CREATE TABLE reviews(
id INTEGER PRIMARY KEY,
stars INT,
business_id INT,
FOREIGN KEY(business_id) REFERENCES businesses(id),
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
);
It will throw syntax error near user_id, and if I put business_id after user_id, it will throw syntax error near business_id...
And if I only put one foreign key there, it will just create the table, tried several times. What's the problem here?
users and businesses are two tables, I'm creating a junction table for them.
Don't mix column definition with constraint definition. Columns first, constraints after:
CREATE TABLE reviews(
id INTEGER PRIMARY KEY,
stars INT,
business_id INT,
user_id INT,
FOREIGN KEY(business_id) REFERENCES businesses(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);

Drop Unique Key and generate new unique key

I have created one table in oracle data base my table script is
CREATE TABLE wsc_widget_bundle (
id VARCHAR (50),
widgetBundle BLOB NULL,
devicesoftwareclass VARCHAR(30) NOT NULL,
widgetProfileId VARCHAR (50) NOT NULL,
bundleHash BLOB NULL,
widgetLocale VARCHAR (6) NOT NULL ,
status INT,
primary key(id),
unique(widgetProfileId, devicesoftwareclass,status),
foreign key(widgetProfileId) references wsc_widget_profile(id)
);
When i create ddl for that is looks like
create table "DEV1"."WSC_WIDGET_BUNDLE"(
"ID" VARCHAR2(50) not null,
"WIDGETBUNDLE" BLOB,
"DEVICESOFTWARECLASS" VARCHAR2(30) not null,
"WIDGETPROFILEID" VARCHAR2(50) not null,
"BUNDLEHASH" BLOB,
"WIDGETLOCALE" VARCHAR2(6) not null,
"STATUS" NUMBER,
constraint "SYS_C00323290" primary key ("ID")
);
alter table "DEV1"."WSC_WIDGET_BUNDLE"
add constraint "SYS_C00323292"
foreign key ("WIDGETPROFILEID")
references "MTP440_DEV1"."WSC_WIDGET_PROFILE"("ID");
create unique index "MTP440_DEV1"."SYS_C00323290" on "MTP440_DEV1"."WSC_WIDGET_BUNDLE"("ID");
create unique index "MTP440_DEV1"."SYS_C00323291" on "MTP440_DEV1"."WSC_WIDGET_BUNDLE"("WIDGETPROFILEID","DEVICESOFTWARECLASS","STATUS");
create index "MTP440_DEV1"."TEST" on "MTP440_DEV1"."WSC_WIDGET_BUNDLE"("DEVICESOFTWARECLASS","STATUS","WIDGETLOCALE","WIDGETPROFILEID");
Now i want to write alter script to alter unique key constrain of my table but as at creation of table I didn't mention the name of my unique key name it is given by system like SYS_C00323291
So how can I write alter script to drop that unique key whose name is not known to me and generation new one
You can find the name of the constraint by querying the user_constraints and user_cons_columns views.
Alter table x
drop constraint pk;
Alter table x
add constraint New_constraint_name PRIMARY KEY (colname);

SQLite foreign key mismatch error

Why am I getting a SQLite "foreign key mismatch" error when executing script below?
DELETE
FROM rlsconfig
WHERE importer_config_id=2 and
program_mode_config_id=1
Here is main table definition:
CREATE TABLE [RLSConfig] (
"rlsconfig_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
"importer_config_id" integer NOT NULL,
"program_mode_config_id" integer NOT NULL,
"l2_channel_config_id" integer NOT NULL,
"rls_fixed_width" integer NOT NULL
,
FOREIGN KEY ([importer_config_id])
REFERENCES [ImporterConfig]([importer_config_id]),
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ImporterConfig]([importer_config_id]),
FOREIGN KEY ([importer_config_id])
REFERENCES [ImporterConfig]([program_mode_config_id]),
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ImporterConfig]([program_mode_config_id])
)
and referenced table:
CREATE TABLE [ImporterConfig] (
"importer_config_id" integer NOT NULL,
"program_mode_config_id" integer NOT NULL,
"selected" integer NOT NULL DEFAULT 0,
"combined_config_id" integer NOT NULL,
"description" varchar(50) NOT NULL COLLATE NOCASE,
"date_created" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY ([program_mode_config_id], [importer_config_id])
,
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ProgramModeConfig]([program_mode_config_id])
)
When you use a foreign key over a table that has a composite primary key you must use a composite foreign key with all the fields that are in the primary key of the referenced table.
Example:
CREATE TABLE IF NOT EXISTS parents
(
key1 INTEGER NOT NULL,
key2 INTEGER NOT NULL,
not_key INTEGER DEFAULT 0,
PRIMARY KEY ( key1, key2 )
);
CREATE TABLE IF NOT EXISTS childs
(
child_key INTEGER NOT NULL,
parentKey1 INTEGER NOT NULL,
parentKey2 INTEGER NOT NULL,
some_data INTEGER,
PRIMARY KEY ( child_key ),
FOREIGN KEY ( parentKey1, parentKey2 ) REFERENCES parents( key1, key2 )
);
I am not sure about SQLite. But I found this link on google. http://www.sqlite.org/foreignkeys.html.
Some of the reasons can be
The parent table does not exist, or
The parent key columns named in the foreign key constraint do not exist, or
The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or
The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns.
Unfortunately, SQLite gives this error all the time without mentioning WHICH foreign key constraint failed. You are left to try to check them one by one, which often doesn't work, and then rebuild the table without the constraints and add them back one by one until you find the problem. SQLite is great in a lot of ways, but this isn't one of them.

Resources