0

I have a users table with columns: user_id, mechanic_id

and

mechanics table with id

I would like to count how many users have the same mechanic.

Users table

+-------------------------+
| user_Id   mechanic_id   |
+-------------------------+
| 1           1,2         |
| 2           2,1         |
| 3           2,1,8,16    |
| 4           1,16,3      |
+-------------------------+

mechanics table

+------+
| id   |
+------+
| 1    |
| 2    |
| 3    |
  ...

Count for $id1 is: 4

Count for $id2 is: 3

Count for $id3 is: 1

Count for $id8 is: 1

Count for $id16 is: 2

Sašo Krajnc
  • 133
  • 2
  • 3
  • 11

3 Answers3

1

Best solution: scrap this table design and rebuild with a properly normalized once. Then a simple join + group by + count query will work.

Worst solution: use MySQL's find_in_set() function:

SELECT mechanics.id, COUNT(user_ID)
FROM mechanics
LEFT JOIN users ON (FIND_IN_SET(mechanics.id, users.mechanic_id) > 0)
GROUP BY mechanics.id
Marc B
  • 356,200
  • 43
  • 426
  • 500
1

I don't know why I am violating the basic principles of database normalization...Each user has usually one mechanic or max 2 or 3, so that's why I decided to store data in users table.

I found solution based on @Marc B:

SELECT count(*) FROM users a 
INNER JOIN mechanics b 
ON (FIND_IN_SET(b.id, a.mechanic_id) > 0)
WHERE b.id = '{$id}' 
group by b.id
Sašo Krajnc
  • 133
  • 2
  • 3
  • 11
0
SELECT  COUNT(user_Id)
FROM    users, mechanics
WHERE   mechanics.id IN (users.mechanic_id)
DevlshOne
  • 8,357
  • 1
  • 29
  • 37