If we are talking about mysql performance, we need to forget about sweet php code. like about orWhere. on a large table is very slow (exception is orWhere on one field). like about JSON field type.
can u post here EXPLAIN both of queries? I can tell you what awaits you under load.
edit: u added query ) great
-
and notifications.notifiable_id is not nullin both case useless -
order by created_at descuseless, useorder by id desc. same result, more performance (if u have incremental id, of course) - as i says, try to not use
JSONfield type.
classic solution on your case is UNION like
(
SELECT *, 'personal' AS norification_type FROM `notifications` WHERE
`notifications`.`notifiable_id` = '960f462f-6a54-42ef-971d-ea3699992dda' AND
`notifications`.`notifiable_type` = 'App\User' AND
JSON_EXTRACT(data, "$.matter_id") = '7'
)
UNION
(
SELECT *, 'group' AS norification_type FROM `notifications` WHERE
`notifications`.`notifiable_id` = '960f462f-6a54-42ef-971d-ea3699992dda' AND
`notifications`.`notifiable_type` = 'App\User' AND
JSON_CONTAINS(`data`, 7, "$.matters")
)
ORDER BY id DESC
LIMIT 1000