简体   繁体   中英

SQL query to select from two tables with if condition

I have two tables Notification and Acknowledgment. Acknowledgment has a field which holds the primary key of Notification table. Basically a Notification will have many Acknowledgments.

Tables: Notification        Acknowledgment

fields: id, notifier        id, parent_id, status

Now I have to choose rows from Notification such that:

  1. there is no Acknowledgment WHERE Acknowledment.parent_id = Notification.id (basically no Acknowledgment for that particular Notification) //or
  2. if there is an Acknowledgment for Notification, then select Notification if any of the Acknowledgments with parent_id = Notification.id has a Acknowledgment.status = someValue

A pseudo SQL code:

   "SELECT * FROM Notification (WHERE id is not present in Acknowledgment.parent_id) OR
   (WHERE id is present in Acknowledgment.parent_id AND Acknowledgment.status=@someValue"

I can break it into simpler queries and achieve this, but I would love to know one single query to get this done..

  SELECT    * 
    FROM    Notification n
            LEFT OUTER JOIN Acknowledgment a ON a.parent_id = n.id
  WHERE     (a.parent_id IS NULL OR a.status = @somevalue)
SELECT n.* FROM Notification n
LEFT OUTER JOIN Acknowledgment a ON a.parent_id=n.id
WHERE a.status IS NULL OR a.status=@someValue

As an alternative to LEFT OUTER JOINS , you can use the EXISTS clause .

For your example:

SELECT *
FROM Notification n
WHERE NOT EXISTS (
   SELECT *
   FROM Acknowledgement
   WHERE parent_id = n.id
) OR EXISTS (
   SELECT *
   FROM Acknowledgement
   WHERE parent_id = n.id AND status = @someValue
)

JOIN s tend to be better optimized in SQL (particularly where, as in my example, you are using more than one on the same table), I just mention this alternative as it is a more direct translation of your pseudo-query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM