0

Let say we have this table:

+─────+────────────+───────+
| id  | parent_id  | code  |
+─────+────────────+───────+
| 1   |            | A     |
| 2   | 1          |       |
| 3   | 1          |       |
| 4   |            | B     |
+─────+────────────+───────+

I need to search for records that have code "A" and those which their parent have code "A" as well. In this case, the query result should return records with id: 1, 2 and 3.

Why those 3?

id 1: has code "A".
id 2: its parent 1 has code "A".
id 3: its parent 1 has code "A".

Any idea will be really appreciated. Thanks.

John Smith
  • 1,357
  • 3
  • 11
  • 21

2 Answers2

1

You can fix it with something like this

SELECT id 
FROM tableName 
WHERE code = "A" OR parent_id IN (SELECT id FROM tableName WHERE code = "A")
Elikill58
  • 3,190
  • 22
  • 17
  • 38
Arxeus
  • 42
  • 5
0
SELECT t1.*
FROM table t1
JOIN table t2 ON t2.id IN (t1.id, t1.parent_id)
WHERE t2.code = 'A'
Akina
  • 31,909
  • 5
  • 12
  • 21