Alchalade
Alchalade

Reputation: 307

Sql conditional Join on different tables

I've to add a notification module on an existing project. My table structure is like on the pic.

Picture :conditionalJoin

as you see on the picture every notification has a type and a releatedID.

Type 1 = reservation is cancelled, releated ID is the id on "reservations" table

Type 3 = account balance is under the given min. limit so releatedID is the id on "account_movements" table

what I'm trying to do is a conditional join to avoid 2 different sql queries;

  1. Get all notifications which are belong to the person
  2. Get notification details from different tables based on "notification.Type"

So the question is can I do it in one query ?

Upvotes: 0

Views: 759

Answers (2)

JNevill
JNevill

Reputation: 50034

Something like the following should work. Basically you specify which records in your notifications table join with records in your reservations table or your account_movements table when you join those in. Use a LEFT JOIN so that ALL of your notification records make it through, and only those records in the reservations table OR the account_movements that have a match make it through.

SELECT 
  n.id,
  n.type,
  n.companyid,
  n.personid,
  n.relatedid,
  n.description,
  r.details as reservation_details,
  am.details as account_movement_details,
  COALESCE(r.details, am.details) AS combined_detail
FROM
  notifications n
  LEFT OUTER JOIN reservations r ON
    n.relatedid = r.id AND
    n.type = 1
  LEFT OUTER JOIN account_movements am ON
    n.relatedid = am.id AND
    n.type = 3

Here is a SQL FIDDLE with the solution as well.

I added in the COALESCE() just to show that since the JOINS are mutually exclusive, you can safely combine columns from your reservations table and your account_movements table into a single column without fear of missing or duplicating any data.

Upvotes: 2

Veve
Veve

Reputation: 6758

If you do a left join, you won't have to have any condition :

SELECT * FROM notifications n
LEFT JOIN reservations r ON n.releatedID = r.id
LEFT JOIN account_movements m ON m.releatedID = m.id

Upvotes: 1

Related Questions