skip to Main Content

Is it possible to combine these two queries into one ?
Meaning: Take the first row if media_group is NULL,
otherwise take all rows with the same media_group

$get_first_record =  R::getRow( 'SELECT * FROM `prn` order by id asc  LIMIT 1');


if(isset($get_first_record['media_group'])){
    $get_media_records = R::getAll( 'SELECT * FROM `prn` WHERE media_group = '.$get_first_record['media_group']);
}

One SQL QUERY for simplify

2

Answers


  1. We can consider using a union query along with a computed column. On MySQL:

    SELECT *
    FROM
    (
        (SELECT *, 1 AS src FROM prn ORDER BY id LIMIT 1)
        UNION ALL
        (SELECT *, 2 FROM prn WHERE media_group = ?)
    ) t
    WHERE
        src = 1 AND media_group IS NULL
        OR
        src = 2;
    

    The logic here is to retain the single record from the first half of the union in case media_group be null (in which case the second half of the union would not return any records). Otherwise, keep only the second half of the union.

    Login or Signup to reply.
  2. This is based on Tim’s answer but removing the need for the parameter:

    SELECT *
    FROM
    (
        (SELECT *, 1 AS src FROM prn ORDER BY id LIMIT 1)
        UNION ALL
        (
            SELECT *, 2
            FROM prn
            WHERE media_group IS NOT NULL
            AND media_group = (SELECT media_group FROM prn ORDER BY id LIMIT 1)
        )
    ) t
    WHERE
        src = 1 AND media_group IS NULL
        OR
        src = 2;
    

    Here’s a db<>fiddle.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search