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,848
  • 3
  • 13
  • 24

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
  • 4,050
  • 24
  • 23
  • 45
Arxeus
  • 62
  • 6
0
SELECT t1.*
FROM table t1
JOIN table t2 ON t2.id IN (t1.id, t1.parent_id)
WHERE t2.code = 'A'
Akina
  • 39,301
  • 5
  • 14
  • 25