Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL server matching two table on a column

I have two tables one storing user skills another storing skills required for a job. I want to match how many skills a of each user matches with a job. The table structure is

Table1: User_Skills
| ID | User_ID | Skill    |
---------------------------
| 1  |  1      |  .Net    |
---------------------------
| 2  |  1      |  Software|
---------------------------
| 3  |  1      |  Engineer|
---------------------------
| 4  |  2      |  .Net    |
---------------------------
| 5  |  2      |  Software|
---------------------------

Table2: Job_Skills_Requirement
| ID | Job_ID | Skill     |
--------------------------
| 1  |  1      |  .Net    |
---------------------------
| 2  |  1      |  Engineer|
---------------------------
| 3  |  1      |  HTML    |
---------------------------
| 4  |  2      |  Software|
---------------------------
| 5  |  2      |  HTML    |
---------------------------

I was trying to have comma separated skills and compare but these can be in different order.

Edit All the answers here are excellent. The result I am looking for is matching all jobs with all users as later on I will match other properties as well.

like image 411
HSharma Avatar asked Dec 23 '22 20:12

HSharma


1 Answers

You could join the tables by the skill columns and count the matches:

SELECT   user_id, job_id, COUNT(*) AS matching_skills
FROM     user_skills u
JOIN     job_skills_requirement j ON u.skill = j.skill
GROUP BY user_id, job_id

EDIT:
IF you want to also show users and jobs that have no matching skills, you can use a full outer join instead.

SELECT          user_id, job_id, COUNT(*) AS matching_skills
FROM            user_skills u
FULL OUTER JOIN job_skills_requirement j ON u.skill = j.skill
GROUP BY        user_id, job_id

EDIT 2:
As Jiri Tousek commented, the above query will produce nulls where there's no match between a user and a job. If you want a full Cartesian products between them, you could use (abuse?) the cross join syntax and count how many skills actually match between each user and each job:

SELECT     user_id, 
           job_id,
           COUNT(CASE WHEN u.skill = j.skill THEN 1 END) AS matching_skills
FROM       user_skills u
CROSS JOIN job_skills_requirement j
GROUP BY   user_id, job_id
like image 91
Mureinik Avatar answered Dec 27 '22 07:12

Mureinik