Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to join elements with condition?

I have two tables: regions and regions_access_purchases.
I need a way to generate for user result table that have info about his current active purchase (access to region).

  1. If user have no any purchased/accessed region he should get full list of regions.
  2. If he have some purchased regions he should get full regions list with appended from right column about his purchaseEndDate.

I tried different joins, but all of them do not work:

SELECT region_id, translite_name,  "purchaseEndDate"  FROM regions
    FULL OUTER JOIN regions_access_purchases reg_purch ON regions.id = reg_purch.region_id
    WHERE user_id = 1 AND 
   "purchaseEndDate" > now()

I am getting only two regions, but I need to get full list of regions, with column from right with "purchaseEndDate". If "purchaseEndDate" is less than now it should not present, but region should be displayed in list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is it’s possible to do such join?

http://sqlfiddle.com/#!15/30e72/2

>Solution :

If you move condition from WHERE to FROM statement and change FULL JOIN to LEFT JOIN you will get expected result:

SELECT * FROM regions
LEFT JOIN regions_access_purchases reg_purch ON regions.id = reg_purch.region_id AND user_id = 1 AND "purchaseEndDate" > now()

P.S. Not sure if you need to add purchaseEndDate to query, added it as you had it in your example.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading