Aashi
Aashi

Reputation: 389

check if comma separated values exist in table

I have a table: users_group

id | group_id | user_ids
---|----------|---------
1  |   1      | 3
2  |   1      | 2
3  |   3      | 2
4  |   2      | 3
5  |   2      | 4
6  |   2      | 2

condition is that user_ids can be inserted only once. But in above case it is inserted for more than one group_id.

I am using this query to insert users_id field within foreach loop: INSERT INTO users_group (group_id, user_ids) VALUES(2,3)

how can I prevent to insert duplicate user_ids

Is there any better query?

Upvotes: 0

Views: 204

Answers (2)

gyaani_guy
gyaani_guy

Reputation: 3209

I think you want to start by creating unique index on the column that you want to have only unique values . In this case that it would be the user_ids column.

Upvotes: 0

Piotr Pasich
Piotr Pasich

Reputation: 2639

Yes, there is a better way to solve this problem, but the solution doesn't imply the query.

Instead of user_id column you should create a new column called user_id and add data like this:

id | group_id | user_id
1  |   1      | 3
2  |   1      | 4
3  |   2      | 3
4  |   2      | 4
5  |   2      | 2
6  |   3      | 2
7  |   3      | 3
8  |   3      | 4

This is called Many to Many relation and makes everything easier. After that you need to only JOIN the tables;

Upvotes: 4

Related Questions