unique constraints for multiple columns in mysql [duplicate] - mysql

This question already has answers here:
How do I specify unique constraint for multiple columns in MySQL?
(14 answers)
Closed 4 years ago.
Guys i have that table in DB
-------------------------------------------------------------
ID | COMPANY_ID | NAME | DESCRIPTION | BARCODE
-------------------------------------------------------------
i want to make a constraints that unique barcodes should be enetered with same companyID .... so how to do that in mysql ??
NB: i cam enter multiple company_id in the table

You need to add a Composite UNIQUE constraint on COMPANY_ID and BARCODE, to your table. This basically means that it will not allow rows having duplicate combination of values, for the said two fields. It can still allow duplicate values individually for either of them.
Eg: (1, 'abc') combination will not be able to exist in more than one row. However, (1, 'abc'), (1, 'def') can exist. So it allows duplicate values individually (Company_id in this example)
Do the following (change table and column name(s) accordingly):
ALTER TABLE your_table_name
ADD CONSTRAINT unique_barcode_company UNIQUE (COMPANY_ID, BARCODE)

Related

mariaDB insert multiple rows where 2 cols not exists

I realize similar questions have been asked before, but I can't seem to find a solution that fits this particular scenario.
I would like to insert multiple rows of data into a mariaDB table where the data must be unique (primary key excluded).
Sample table:
enrollmentsID
classID
userID
1
1
2
2
1
3
3
1
4
4
2
2
5
2
7
So if I want to insert a number of rows, I don't want to duplicate what's already present.
The general idea is something like:
INSERT INTO `enrollments` (`enrollmentsID`, `classID`, `userID`)
VALUES (NULL,1,2),(NULL,1,3),(NULL,1,4),(NULL,1,5)
WHERE NOT EXISTS (
SELECT `enrollments`.`classID`, `enrollments`.`userID`
FROM `enrollments`)
Here, userID 5 would insert but userID 3 and userID 4 would be ignored.
Unfortunately, the WHERE is causing issues... Thanks for any help provided.
As P.Salmon mentioned in the comments, a UNIQUE index on the two columns is likely what you need. The index needs to be on both columns, not a UNIQUE index for each column.
ALTER TABLE enrollments
ADD UNIQUE INDEX (`classID`,`userID`)
From there you can do INSERT INGORE INTO instead of INSERT INTO and that will only insert the unique entries.

Why does the default constraint not work in mysql? [duplicate]

This question already has answers here:
Column count doesn't match value count at row 1
(6 answers)
Closed 2 years ago.
Error Code: 1136. Column count doesn't match value count at row 1
roll_no INT PRIMARY KEY NOT NULL unique,
name CHAR(15) NOT NULL,
class integer(3),
section CHAR(1),
sibling boolean default false);
insert into school
values(1,'ramesh',12,'D');
If you don't provide values for all the columns, you need to explicitly state what columns the values refer to:
insert into school(roll_no, name, class, section)
values(1, 'ramesh', 12, 'D');
You didn't specify the column names in the insert, and therefore MySQL is expecting data for all columns. Qualify your target column names, and the insert should work:
INSERT INTO school (roll_no, name, class, section)
VALUES
(1, 'ramesh', 12, 'D');
Best practice for SQL inserts is to always list out the target columns for the insert. One reason for this is that, if you don't, an insert statement could break if either a) the number of columns changes, or b) the order of columns in the table changes.

It is possible for a foreign key to store values that aren't matching primary key values? [duplicate]

This question already has answers here:
Many-to-many relationships examples
(5 answers)
Closed 3 years ago.
Database design question. Let's say I have two tables: [PEOPLE] and [FRUITS]:
[PEOPLE]
- id
- fruit_id
- many other columns
[FRUITS]
- id
- name
- many other columns
Which are related by PEOPLE.fruit_id = FRUITS.id.
So fruit_id can store any value from id of [FRUITS] table. But the problem is, I want fruit_id to store values besides those, like 'All of the fruits', 'Some of the fruits', 'None of the fruits'.
I already used NULL as a flag for 'None of the friuts' value.
What is the best solution in this situation?
And out of curiosity I wanna ask: What to do in the situation when I want one foreign key to store values of multiple primary keys? For example: there is one more table [VEGETABLES]:
[VEGETABLES]
- id
- name
- many other columns different from [FRUITS]
And I want PEOPLE.fruits_id to be able to store values from both FRUITS.id and VEGETABLES.id.
I am not native English speaker, so forgive me for mistakes.
Storing the fruit_id within the people table allows you to assign one or none (NULL) fruit to a person.
If you want to assign several fruits to one row in the people table you need a pivot table (one to many)
e.g
PEOPLE_FRUITS
- people_id
- fruit_id
- unique key people_id, fruit_id
This way you can assign none, one or many fruits to a row in the people table.
The unique key would disallow assignment of the same fruit to the same person multiple times.
Same applies to vegetables

MySQL - update row if some column value equals else insert row (NO DUPLICATE KEY)

I have a table that stores meta values, however, in insert/update I want to perform - there is no unique key (not even a combination of columns).
1 column stores ID of a post, 1 a varchar key of a meta value and 1 holds the meta value...
Now the thing is, the table CAN contain duplicate rows, easily, this can happen:
id_post | key | value
5 'bobber' 4
3 'locer' 2
5 'bobber' 4
Now what I want to do is to do a variation of insert or duplicate key update, problem is, I don't have the key that would trigger the update.
If the key value is already existing in the table, I want to update the corresponding value column(s). If it is not, I want to insert a brand new row.
All I found ends up with adding a key constraint, which is something I can't do.Also, I do not want to create a stored procedure/function.
Any help please? Thank you :-)

MySQL Insert (conditional) unique value once per user

I wasn't sure how to explain this in the title, but what I have is a table like this:
user_id | subscription_id
6 12
6 10
12 6
4 12
Each user can subscribe to all other users, but is it possible to prevent a user from subscribing to another user twice through a INSERT query?
As my subscription_id is not unique, this happens:
user_id | subscription_id
6 12
6 12
And I want to avoid that. As far as I know INSERT IGNORE, INSERT UPDATE and ON DUPLICATE only works with unique keys.
You need to set up your database table to have a composite primary key for user_id AND subscription_id
That way each row has to be unique across both the columns.
See: How to properly create composite primary keys - MYSQL
The only reliable and easy way to make sure that a tuple cannot occur more than once inside a single table is either:
Use a spanning unique key
Use a spanning primary key
Maybe triggers
The first two are roughly the same, but unique keys treat null values as distinct as well, so that might not work for you.
ALTER TABLE user_subscriptions ADD PRIMARY(user_id, subscription_id);