spajak
spajak

Reputation: 603

Select specific record or records with the same value in a column

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)?

Upvotes: 0

Views: 118

Answers (1)

spencer7593
spencer7593

Reputation: 108400

The following query will return a resultset that matches the specification.

SELECT DISTINCT COALESCE(t.name,s.name) AS `name`
  FROM `tbl` s
  LEFT
  JOIN `tbl` t
    ON t.group = s.group
 WHERE s.name = 'a1'

If a row with name = 'a1' exists in the table, that row will be returned. The query will also return values of name that have a group value that matches any group value for a row with name = 'a1'.

Upvotes: 1

Related Questions