I'm having an issue trying to avoid partial duplicate results with a MySQL query. I admit I'm really new at MySQL but I have learned from research on SO that the schema I'm about to lay out for you below could definitely be done a better way (the linked_users column of the users table should be a separate table). However, I cannot change the way it is set up right now.
I'm trying to return the user names of the user ids assigned to each item in t2 or the user names of the users who are linked to those users. The query is returning two sets of names for each item, however. I think this is happening because it is searching them all twice, and I've attempted to read this tutorial on SO regarding returning multiple values from multiple tables but I can't seem to wrap my mind around the JOINS and UNIONS and whatnot.
My question is two-fold:
- What can I do to solve this issue without changing the way the database is set up?
- How should the database be changed to better allow for queries like this in the future?
Thank you for your time.
Schema:
create table users (user_id int, user_name varchar (55), linked_users varchar (55));
insert into users( user_id, user_name, linked_users)values(1, 'user1', '2,154,4,45');
insert into users( user_id, user_name, linked_users)values(2, 'user2', '13,1,200');
create table t2 (t2_id int, user_id int);
insert into t2( t2_id, user_id)values(1, 2);
insert into t2( t2_id, user_id)values(2, 1);
insert into t2( t2_id, user_id)values(3, 1);
insert into t2( t2_id, user_id)values(4, 2);
insert into t2( t2_id, user_id)values(5, 3);
Query:
SELECT t.*, u.user_name
FROM t2 t, users u
WHERE t.user_id = u.user_id
OR find_in_set(t.user_id, u.linked_users) > 0