I have this table with data:
NAME | GROUP
------------
a1 | A
a22 | A
c1 | C
c2 | C
s1 | NULL
t1 | NULL
How to select record named a1 and if this record has a group <> NULL include also other items from the same group?
I’ve tried subquery:
SELECT `name`, `group` FROM `tbl`
WHERE (`name` = 'a1' AND `group` IS NULL) OR `group` = (SELECT `group` FROM `tbl` WHERE `name` = 'a1')
EXPLAIN:
id select_type table type possible_keys key key_len ref rows
1 PRIMARY tbl ALL PRIMARY NULL NULL NULL 6 Using where
2 SUBQUERY tbl const PRIMARY PRIMARY 386 const 1
This works but I’m not sure if it’s 100% correct and efficient. Looking for a better solution, maybe with JOIN?
MySQL internals question: Is inner SELECT query executed for every searched record in the outer table? Is result of this query cached (like SELECT SQL_CACHE query)?
The following query will return a resultset that matches the specification.
If a row with
name = 'a1'exists in the table, that row will be returned. The query will also return values ofnamethat have agroupvalue that matches anygroupvalue for a row withname = 'a1'.