Liuqing Hu
Liuqing Hu

Reputation: 1980

How to select out all record when a condition has parent id?

The table will like this:

 id   content  parent_id  
 1     first      0
 2     second     1

question is: if if select id = 2 how could i select its parent record within a query

   SELECT *
   FROM
      table tb1
   LEFT JOIN
      table tb2
   ON
      tb1.parent_id = tb2.id
   WHERE
      tb1.id = 2

when id = 2 result will return :

 1  first  0
 2  second 1  

not just return :

 2 second 1

thank u

Upvotes: 0

Views: 81

Answers (2)

Pooja
Pooja

Reputation: 170

Here in your query there is no matching field hence it is returning empty rows!! in parent_id change its value from 0,1 to 1,2

by doing that tb2.id=tb1.parent_id will return true and you will get output hope that helps!!

Upvotes: 0

Sanal K
Sanal K

Reputation: 733

Try this

SELECT id,content,parent_id FROM table_name 
WHERE (SELECT parent_id FROM table_name WHERE id=2) IN (id,parent_id)

Upvotes: 1

Related Questions