Sql conditional Join on different tables

こ雲淡風輕ζ 提交于 2020-01-06 14:47:31

问题


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

Picture :

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 ?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/26715656/sql-conditional-join-on-different-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!