I have a group feature on my website that allows 1 user to put the userids of any of his or her friends into an invitedusers column. I need to do an SQL search to determine whet
This should do the job:
SELECT userid, name... FROM mytable WHERE FIND_IN_SET('234', invitedusers) !=0;
Assuming that you're really using 234,394,479
as value of one column (you at least should use ,234,394,479,
to be able to do WHERE invited LIKE '%,234,%'
in your query) you should rebuild your user tables, remove field invited_users
and create table like this:
CREATE TABLE invited_users (
id INT AUTO_INCREMENT,
owner_id INT, -- Who's input it is
target_id INT, -- What's the target user
PRIMARY KEY ( id),
UNIQUE ( owner_id, target_id),
-- Indexes (FOREIGN KEYs!) to users table
);
And than just select list of users who invited user 234 with query:
SELECT users.id, users.name
FROM invited_users
INNER JOIN users ON invited_users.owner_id = users.id
GROUP BY users.id
WHERE invited_users.target_id = 234
I'm not sure if this is the best way but:
where concat(',',invitedusers,',') like '%,234,%'
So in your example ,234,
is inside ,234,394,479,
You may not want to store a comma delimited list in a column, but since you are:
SELECT userid, name FROM mytable
WHERE invitedusers = '(' + '234' + ')' -- One and only one entry
OR invitedusers LIKE '(' + '234' + ',%' -- First entry
OR invitedusers LIKE '%,' + '234' + ',%' -- Middle entry
OR invitedusers LIKE '%,' + '234' + ')%' -- Last entry
I have modified based on EBarr's comment. There are four cases to check for. This assumes you are storing the data with a ( prefix and a ) suffix and separating everything with commas.
Here are some tests to prove that it works:
/* Tests */
INSERT INTO @mytable SELECT 11, 'a', '(234)' -- Should get returned
INSERT INTO @mytable SELECT 12, 'b', '(1234)'
INSERT INTO @mytable SELECT 13, 'c', '(92349)'
INSERT INTO @mytable SELECT 13, 'd', '(2345)'
INSERT INTO @mytable SELECT 21, 'a', '(234,567)' -- Should get returned
INSERT INTO @mytable SELECT 22, 'b', '(1234,567)'
INSERT INTO @mytable SELECT 23, 'c', '(92349,567)'
INSERT INTO @mytable SELECT 23, 'd', '(2345,567)'
INSERT INTO @mytable SELECT 31, 'a', '(567,234)' -- Should get returned
INSERT INTO @mytable SELECT 32, 'b', '(567,1234)'
INSERT INTO @mytable SELECT 33, 'c', '(567,92349)'
INSERT INTO @mytable SELECT 33, 'd', '(567,2345)'
INSERT INTO @mytable SELECT 41, 'a', '(123,234,789)' -- Should get returned
INSERT INTO @mytable SELECT 42, 'b', '(123,1234,789)'
INSERT INTO @mytable SELECT 43, 'c', '(123,92349,789)'
INSERT INTO @mytable SELECT 43, 'd', '(123,2345,789)'
SELECT userid, name FROM @mytable
WHERE invitedusers = '(' + '234' + ')' -- One and only one entry
OR invitedusers LIKE '(' + '234' + ',%' -- First entry
OR invitedusers LIKE '%,' + '234' + ',%' -- Middle entry
OR invitedusers LIKE '%,' + '234' + ')%' -- Last entry