1

i am trying to write a query in mysql, where my table structure is given below

place_id    state_id    city_id     place_name  
    1           0           0           United States   
    2           1           0           Alabama     
    3           0           2           Auburn  
    32          0           0           Canada  
    33          32          0           Alberta     
    34          0           33          Calgary 

here i have united states id which is 1, using this id i want to retrieve all the states in united states and the cities of each state. Here,

  1. if state_id and city_id is 0 then it is a country
  2. if city_id is 0 then it is a state
  3. if state_id is 0 then it is a city
  4. place id is auto_increment

please some one help me, thank you.

2
  • 1
    Post your expected output. Commented Mar 9, 2017 at 10:05
  • I don't envy you your data model. :-( Commented Mar 9, 2017 at 10:20

1 Answer 1

1

For United States you could use a self join for joining the same table 3 times.

select t1.place_name, t2.place_name, t3.
from my_table t1 
inner join my_table t2 on  t1.place_id = t2.state_id 
inner join my_table t3 on t3place_id =   t3.city_id
where t1.place_name  ='United States';
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for replying self joining solved my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.