473,606 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Table Joins on more than one field

das
Hello all,
Can someone help me with this SQL?

1) EMPLOYEE table has columns 'employee_id' and 'emp_sid' and other
columns

2) EMPLOYEE_BENEFI TS table has a column called employee_entity , this
column can be joined to either 'employee_id' OR 'emp_sid' but not both
in the EMPLOYEE table.

3) EMPLOYEE_TRACK table has column called employee_track_ entity, this
column can be joined to the employee_benefi ts_id (PK) of the
EMPLOYEE_BENEFI TS table.

I am listing the sql for the tables (the tables shows only the columns
in question)

CREATE TABLE [dbo].[EMPLOYEE] (
[employee_id] [int] IDENTITY (1, 1) NOT NULL ,
[empsid_id] [int] NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[EMPLOYEE_BENEFI TS] (
[employee_benefi ts_id] [int] IDENTITY (1, 1) NOT NULL ,
[employee_entity] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[EMPLOYEE_TRACK ] (
[employee_track_ id] [int] IDENTITY (1, 1) NOT NULL ,
[employee_track_ entity] [int] NOT NULL
) ON [PRIMARY]
GO

SELECT * FROM EMPLOYEE e
INNER JOIN
EMPLOYEE_BENEFI TS eb ON (e.employee_id = eb.employee_ent ity OR
e.empsid_id = eb.employee_ent ity)
INNER JOIN
EMPLOYEE_TRACK et ON eb.employee_ben efits_id = et.employee_tra ck_entity
The above SQL I wrote is this: the second inner join uses a OR to join
either of the columns in the first table EMPLOYEE. There is performance
degradation with this SQL. With huge data It takes about 30 seconds to
execute. I know this is not the perfect way to do it, can anyone of the
SQL Gurus please enlighten me to a faster approach?

If I dont use the OR I can try left join on the same table
EMPLOYEE_BENEFI TS twice by changing the join types, but If I did this
what table alias can I use to join to the 3rd table?

SELECT * FROM EMPLOYEE e
LEFT JOIN
EMPLOYEE_BENEFI TS eb1 ON e.employee_id = eb.employee_ent ity
LEFT JOIN
EMPLOYEE_BENEFI TS eb2 ON e.empsid_id = eb.employee_ent ity
INNER JOIN
EMPLOYEE_TRACK et ON [???].employee_benef its_id =
et.employee_tra ck_entity

thanks
adi

[Sorry I am posting this twice, on SQL Programming forum too]

May 4 '06 #1
3 2029
das (Ad*******@gmai l.com) writes:
SELECT * FROM EMPLOYEE e
INNER JOIN
EMPLOYEE_BENEFI TS eb ON (e.employee_id = eb.employee_ent ity OR
e.empsid_id = eb.employee_ent ity)
INNER JOIN
EMPLOYEE_TRACK et ON eb.employee_ben efits_id = et.employee_tra ck_entity
The above SQL I wrote is this: the second inner join uses a OR to join
either of the columns in the first table EMPLOYEE. There is performance
degradation with this SQL. With huge data It takes about 30 seconds to
execute. I know this is not the perfect way to do it, can anyone of the
SQL Gurus please enlighten me to a faster approach?
You could try using UNION:

SELECT *
FROM EMPLOYEE e
JOIN EMPLOYEE_BENEFI TS eb ON e.employee_id = eb.employee_ent ity
JOIN EMPLOYEE_TRACK et
ON eb.employee_ben efits_id = et.employee_tra ck_entity
UNION
SELECT *
FROM EMPLOYEE e
JOIN EMPLOYEE_BENEFI TS eb ON e.empsid_id = eb.employee_ent ity
JOIN EMPLOYEE_TRACK et
ON eb.employee_ben efits_id = et.employee_tra ck_entity

Or even:

SELECT *
FROM (SELECT *
FROM EMPLOYEE e
JOIN EMPLOYEE_BENEFI TS eb ON e.employee_id = eb.employee_ent ity
UNION
FROM EMPLOYEE e
JOIN EMPLOYEE_BENEFI TS eb ON e.empsid_id = eb.employee_ent ity)
AS eb
JOIN EMPLOYEE_TRACK et ON
eb.employee_ben efits_id = et.employee_tra ck_entity

The latter is uses a derived table and is more compact. Which performs
the best, I don't know.

A derived table is logically a temp table within the query, but SQL Server
may recast computation order. They are a very powerful tool to write
complex SQL queries.

You may have to replace the * in the derived table, if there are name
clashes between the tables.
If I dont use the OR I can try left join on the same table
EMPLOYEE_BENEFI TS twice by changing the join types, but If I did this
what table alias can I use to join to the 3rd table?

SELECT * FROM EMPLOYEE e
LEFT JOIN
EMPLOYEE_BENEFI TS eb1 ON e.employee_id = eb.employee_ent ity
LEFT JOIN
EMPLOYEE_BENEFI TS eb2 ON e.empsid_id = eb.employee_ent ity
INNER JOIN
EMPLOYEE_TRACK et ON [???].employee_benef its_id =
et.employee_tra ck_entity


You would have to write

coalaesce(eb1.e mployee_benefit s_id, eb2.employee_be nefits_id)

but I would stay away from this solution.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx

May 4 '06 #2
das
thanks Erland, thats useful information.

I however used another approach, based on some logic I determine which
join to use (not both anymore) so now there are 2 sql's with different
joins based on this condition.

thanks again for the help.

May 10 '06 #3
>> Can someone help me with this SQL? <<

Not really, because you do not have an RDBMS. You have a bunch of
poorly designed non-tables written in SQL.
1) EMPLOYEE table has columns 'employee_id' and 'emp_sid' and other columns <<

The table name EMPLOYEE (all uppercase so it ihard to read or you are
using punchcards for the one employee you have -- singular names mean
one entity). If this table is for personnel data (a set), not for each
employee as if they records in a sequential file, why did you give it
such a bad name. Which one of these two columns is the PRIMARY KEY?
Oh, you have no keys at all!!
2) EMPLOYEE_BENEFI TS table has a column called employee_entity , this column can be joined to either 'employee_id' OR 'emp_sid' but not both in the EMPLOYEE table. <<
You actually used a postfix of entity! So much for data modeling and
ISO-11179 specs! You also missed the whole idea of PK-FK constraints --
There is no OR option in the concept. I think that some early network
DBMS system had "variant pointers" that could work liekthat, but I
owuld have to research it
3) EMPLOYEE_TRACK table has column called employee_track_ entity, this column can be joined to the employee_benefi ts_id (PK) of the EMPLOYEE_BENEFI TS table.<<
Again, a singular name so we have only one track. Since IDENTITY can
never be a key by definition, EMPLOYEE_BENEFI TS has no key to
reference. Don't your benefit programs have names, tax ids, or
something you can validate and verify?

Again, you are creating a pointer chain DBMS system in SQL, but do not
have the background to realize that you are re-inventing a square
wheel.

CREATE TABLE Personnel
(employee_id CHAR(9) NOT NULL PRIMARY KEY, -- use legally required id
...);

CREATE TABLE EmployeeBenefit s
(employee_benef its_id INTEGER NOT NULL PRIMARY KEY,
employee_id CHAR(9) NOT NULL
REFERENCES Personnel(emplo yee_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

CREATE TABLE EmployeeTracks
(employee_track _id INTEGER NOT NULL PRIMARY KEY,
.. );
The above SQL I wrote is this: the second inner join uses a OR to join either of the columns in the first table EMPLOYEE. There is performance degradation with this SQL. With huge data It takes about 30 seconds to execute. <<
You are worried about performance degradation?? You forgot the lack of
data integrity caused by two keys.
I know this is not the perfect way to do it, can anyone of the SQL Gurus please enlighten me to a faster approach? <<


Clean up the DDL. Get real keys instead of that IDENTITY crap. Learn
basic data modeling. Fix the multiple key problem. And stop putting
SELECT * in production code.

I saw a problem like this once a few decades ago. Two companies had
merged because they wer tired of competing in the same market (welding
supplies, same products). One company coded its inventory by the
location in the warehouse (makes picking orders very easy) and the
other coded by the type of welding done (aluminium, brass, underwater,
etc.). The warehouses were arranged very differently becuase of the
encoding. Are you familar with the Japanese housing numbering system
versus the United States?

They wanted a combined inventory and catalog, but their customers and
personnel were too used to one system or the other and the politics
were awful.

What they needed as a kludge was one and only one SKU code and a
conversion table in the computer and a pair of codes on the labels.
Until they could design a good SKU code.

Did this cost a lot of time and money? You bet! In fact, it killed the
merger. Each warehouse was an island of data, so there was no timely
way to move inventory across the two SKU codes to fill orders.
Someone asks for 5 Widgets and 2 are under code #A and 3 are under code
#B in another warehouse, but nobody knew!

Have you been to a Barnes & Noble lately? Look at the company sticky
label that goes over the pre-printed ISBN code. Same expensive, stupid
design flaw that you and the welding supplies companies had.

May 10 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

36
4636
by: toedipper | last post by:
Hello, I am designing a table of vehicle types, nothing special, just a list of unique vehicle types such as truck, lorry, bike, motor bike, plane, tractor etc etc For the table design I am proposing a single column table with a field name called vehicle_type and this will contain the vehicle type. Sot it will be
3
23445
by: Jon Ole Hedne | last post by:
My Access 2002-application need to work with tables from both Oracle and Access. To solve this, I want to run some querys on three views in Oracle and import the results into temporary Access-tables. I have tried this: conn.Provider = "Microsoft.Jet.OLEDB.4.0" conn.ConnectionString = "data source=" & datafil & ";Jet OLEDB:Database Password=" conn.Open datafil
5
1868
by: mm nn | last post by:
Hi, I want to create a table like this: ID Autonum Datefld Date Cat Text Itm Text tCount Number
5
4323
by: Ilan Sebba | last post by:
When it comes to adding records in related tables, Access is really smart. But when I try to do the same using ADO, I am really stupid. Say I have two parent tables (eg Course, Student) and one child table (StudentProgress). The course progress records how a student progresses on a course. I have one course (History) and one student called Maya. I now want to record her grade (64). If I do this in Access using a form, then the form...
5
2065
by: Stewart Allen | last post by:
Hi all, I'm designing a club database and have encountered a problem when trying to extract the total amount of fees that a Student/Family is suppose to pay during their time of membership. I've already designed the tables and relationships but I want your advice to see if my design was right. In my older version a member pays the fees but when there's 2 or more members that belong to a family (brother, sister, mother, father etc),...
3
2772
by: vonclausowitz | last post by:
Hi All, I was thinking of creating a table in my database to index all words in the database. That way I can quickly search for one or more words and the index table will return the words and records I need. For example the iTable would look like this:
2
5758
by: Jody | last post by:
Hi I've been working on a database which basically incorporates 3 tables to describe say a widget which is either sold or leased. I have the Widget table which stores the information related to the widget itself. I then have a WidgetSale table which stores only information related to the sale of the widget (advertised price, headline, copy, date of sale
3
1467
by: Macbane | last post by:
Hello All, This has been bugging me for too long. I have a database that records medical interventions. I am familiar with the theory behind normalisation but am unsure what to do with the following data. Firstly, I have a main table which records the specifics of the intervention (date, reporter, details, location etc). It has links and the database is normalised ok as far as I can make out. However, I have 6 check box fields in...
11
2641
by: Paul H | last post by:
Suppose I have a table called tblPeople and I want a field to illustrate whether each person prefers cats or dogs. I could do it one of three ways. 1. A plain text field Create a text field in tblPeople called PreferredPet. 2. A lookup field that stores text values. Create a text field in tblPeople called PreferredPetID and use it to lookup an identical text field in tblPreferredPets.
0
18500
NeoPa
by: NeoPa | last post by:
Introduction Joins, in SQL, are a way of linking Recordsets together. They involve restricting which data is returned in the output Recordset. When no join is specified but two Recordsets are, then a cartesian product is produced which specifies no restrictions. Conceptually, a JOIN is applied before any WHERE clause which may be specified. NB. Full Outer Joins are not supported in Access (Jet) SQL. When Recordsets are JOINed they...
0
8432
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8428
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8299
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6753
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5962
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5456
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3919
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3964
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2442
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.