Search code examples
mysqlsqlgroup-bysubquerydistinct

How to skip rows from table in mysql


I have one table which has the following data, I want to skip row 3, just want to fetch OPEN status only once, I am using below query but it skipping wor 5 as well.

    SELECT t.*
FROM emailEvent t
  JOIN 
    ( SELECT MIN(id) AS minid
      FROM emailEvent WHERE email_id = 3
      GROUP BY status
    ) AS grp
    ON grp.minid = t.id
WHERE (t.email_id = 3)

I came up with this as a solution but not sure if there are any other best solution for this

 SELECT t.*
FROM emailEvent t
WHERE t.status != "Open" and t.email_id = 3
UNION
(
SELECT et.*
FROM emailEvent et
WHERE et.status = "Open" and et.email_id = 3
ORDER BY et.createdAt DESC LIMIT 1
)

enter image description here

I want the result to be look like something like this enter image description here


Solution

  • SELECT *
    FROM
     (
       SELECT t.*, 
          min(id) over (partition by status) as min_id
       FROM emailEvent t
       WHERE (t.email_id = 3)   -- only email 3
     ) AS dt
    WHERE id = min_id           -- only for 'Open' status
       OR status <> 'Open'
    

    For older releases not supporting Windowed Aggregates:

    select * 
    from emailEvent
    where email_id = 3
    and 
      (
       e.status <> 'Open'
       or id in (select min(id)  -- only for 'Open' status
              from emailEvent 
              where status = 'Open'
              and email_id = 3)
      )