Jump to content

Simple database interaction - if you know how.


johnsmith153

Recommended Posts

I have 2 tables and am trying to conduct an SQL query. I simply need to know how to use a JOIN when two fields in each table are needed to match the records up. I would rather not create another field in each table.

 

I have put my query below which would work other than for what is obviously not possible ("ON xyz=xyz && abc=abc" etc.)

 

Table 1 "Employees"

 

employeeDept / deptEmployeeRef / name / wage

 

A / 2 / Dave Smith / 2000

B / 2 / Robert Brown / 2500

 

 

Table 2 "Deductions"

 

monthNo / employeeDept / deptEmployeeRef / deduction

 

32 / B / 2 / 300

32 / C / 2 / 300

32 / A / 3 / 300

33 / B / 2 / 500

 

 

Each department has employees starting from number 1 so two fields are needed in each table to match the records up.

 

SELECT t1.name, (t1.wage - t2.deduction) FROM $tableName1 AS t1 LEFT JOIN $tableName2 AS t2 ON t1.employeeDept=t2.employeeDept && t1.deptEmployeeRef=t2.deptEmployeeRef WHERE t2.monthNo = '32'

 

So this should return:

Dave Smith 2000

Robert Brown 2200

 

Link to comment
Share on other sites

I think you should considering laying out like this:

 

Table 1 "Employees"

 

employeeID/employeeDept / deptEmployeeRef / name / wage

 

1 / A / 2 / Dave Smith / 2000

2 / B / 2 / Robert Brown / 2500

 

 

Table 2 "Deductions"

 

monthNo / employeeID / deduction

 

32 / 0 / 300

32 / 1 / 300

32 / 2 / 300

33 / 3 / 500

 

 

employeeID should be auto-incrementing so it's unique - no two employees will have the same. Having a ref number per dept. might be what you need, I don't know the situation, but having a unique identifier for each entry is advisable, the rest is changeable data. This would make your JOIN statement easier

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.