views:

34

answers:

2
SELECT
    description
FROM 
    diagnosis_mapping 
LEFT JOIN
    diagnosis_codes
ON
    diagnosis_codes.codeid = diagnosis_mapping.codeid

SELECT
    description
FROM 
    diagnosis_mapping 
LEFT JOIN 
    diagnosis_codes
ON
    diagnosis_codes.codeid = diagnosis_mapping.secondarycodeid

How to merge these 2 queries and get info in a single resultset? In first i need to match with codeid and in second i need to match with secondarycodeid to the same mastertable to fetch the description of both.

+5  A: 

You can do two joins in one query, just give an alias to the table names so MySQL knows what you want to get:

SELECT
    a.description desc_a,
    b.description desc_b
FROM 
    diagnosis_mapping 
LEFT JOIN
    diagnosis_codes a
ON
    a.codeid = diagnosis_mapping.codeid
LEFT JOIN 
    diagnosis_codes b
ON
    b.codeid = diagnosis_mapping.secondarycodeid

In this example, a is an alias for the first diagnosis_codes table and b to the other. When you give alias names to the tables, MySQL (and any other SQL aware database) treats them basically as two separate tables and fetches data from them independently.

Tatu Ulmanen
Also best give an alias to the result fields (`a.description desc_a, b.description desc_b`) as most frameworks returning an associative array (f.i. PHP's `mysql_fetch_assoc`) ignore the table name component and would otherwise give you back only one `description` field.
Wim
@Wim, you're absolutely right, my example wouldn't be very usable without them. I've edited my answer.
Tatu Ulmanen
Its Working. Thanks. Even the idea of giving alias to the resultfields is cool. Its great. Thanks for all your help in getting me done.
ASD
A: 
SELECT description FROM (diagnosis_mapping LEFT JOIN diagnosis_codes ON (diagnosis_codes.codeid = diagnosis_mapping.codeid)) LEFT JOIN diagnosis_mapping ON (diagnosis_codes.codeid = diagnosis_mapping.secondarycodeid)

Not sure if thats what you need, but try ;] (might need some spelling checking and adding some "AS" if there are any sql errors)

PawelMysior