开发者

How to use a value in WHERE clause from a comma separated string in a MySQL Table?

How to get records from a table that contains 24 as DeptID. I've added the table structure. What is the SQL query to get the ID and NAME that contains 24 as DeptID?

Users:
------
ID  NAME    DeptID
--- -----   ----开发者_开发知识库---
1   balaji  1,136,12,53,48,2,153,45,78,53,10,3,143,53,46,49
2   scott   24,90,120
3   balraj  43,9,24,901


We can use find_in_set function in MySQL.

$deptid="24";

QUERY is

select * from Users where FIND_IN_SET('$deptid', DeptID);


After the last comment from the OP I'll do an answer because it as better formating than comments. Sincerely, it would do you a lot of good to read some things about relational databases before working with them.

But here is how I think your data should be stored:

  • User table : (ID, name, other columns)
  • Dept table : (ID, name, other columns)
  • UserDept table : (userId, deptId)

Then when you want to get a user's dept ID in one string you can do something like

SELECT ID, name,
GROUP_CONCAT(deptId SEPERATOR ", ") AS deptIdList
FROM User
INNER JOIN UserDept 
On UserDept.userId = User.ID
GROUP BY(User.ID)

Or if you want all the user from department 53:

SELECT ID, name
FROM User
INNER JOIN UserDept
On UserDept.userId = User.ID
Where UserDept.deptId = 53

Or maybe all the departments names from the user 10:

SELECT ID, name
FROM Dept
INNER JOIN UserDept
On UserDept.deptId = Dept.ID
Where UserDept.userId = 10

As you can see, everything becomes simple with a normalized database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜