Click here to Skip to main content
15,031,361 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
table1: (patient_id, patient_name, complaint_id_right, complaint_id_left)
table2: (complaint_id, complaint_name)

I have two tables as above, one for patients(table1) and other as list table (table2)

I cannot display complaint_name instead of both complaint_id_right and complaint_id_left at the sametime, because i use table2 as list for both fields (complaint_id_right, complaint_id_left).
How to do it?

What I have tried:

select patient_id, patient_name, complaint_name, complaint_name
from table1
left join table2
on table1.complaint_id_right = table2.complaint_id and table1.complaint_id_left = table2.complaint_id
Posted
Updated 11-Jan-21 22:22pm

You need to do a separate JOIN per "link".
Try this:
SQL
SELECT p.patient_id, p.patient_name, cl.complaint_name, cr.complaint_name
  FROM table1 p
LEFT JOIN table2 cr
  ON p.complaint_id_right = cr.complaint_id
LEFT JOIN table2 cl 
  ON p.complaint_id_left = cl.complaint_id

But do yourself a favour and use more sensible names! "table1" should be "Patients", "table2" should be "Complaints", "patient_id" should be "ID", "complaint_id" should be "ID" and so on. You don't need to include the table name in its ID column since you will always refer to it via the table name anyway.

I also suspect that your design is flawed - "left" and "right" columns should probably be a third table linking patients to complaints:
HasComplaint:
ID           (IDENTITY or UNIQUEIDENTIFIER)
PatientID    (Foreign key to Patients.ID)
ComplaintID  (Foreign key to Complaints.ID)
This allows for a patient with one complaint, two complaints, or a dozen complaints.
   
Comments
Maciej Los 12-Jan-21 4:14am
   
5ed!
Another way is to use Common Table Expressions[^].

SQL
;WITH CTE AS
(
  SELECT pa.patient_id, pa.patient_name, 'left' comp_type, co.complaint_name
  FROM table1 pa LEFT JOIN table2 co ON pa.complaint_id_left = com.complaint_id
  UNION ALL
  SELECT pa.patient_id, pa.patient_name, 'right' comp_type, co.complaint_name
  FROM CTE pa LEFT JOIN table2 co ON pa.complaint_id_right = table2.complaint_id 
)
SELECT *
FROM CTE


For further details, please see:
WITH common_table_expression (Transact-SQL) - SQL Server | Microsoft Docs[^]
Mastering Common Table Expression or CTE in SQL Server[^]

Good luck!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900