how to write this self join query in mysql

自闭症网瘾萝莉.ら 提交于 2020-01-01 19:21:08

问题


Hello I have a table structure like this

products_id | model_num | master_model_num
   1        |  cth001   |    0 
   2        |  cth002   |    0
   3        |  cth003   |    cth001
   4        |  cth004   |    cth001
   5        |  cth005   |    0
   6        |  cth006   |    cth002

My Problem

I will provide the products_id to the table and it will get all product ids whoes master_model_num is equal to the model_num of the given products_id

I have tried following query but it doen't generate the result that I want

SELECT p.products_id 
FROM products p,products pp 
WHERE p.products_id=pp.products_id 
AND p.products_model=pp.products_master_model 
AND p.products_id='1' 

回答1:


SELECT pp.products_id
    FROM products p
        INNER JOIN products pp
            ON p.model_num = pp.master_model_num
    WHERE p.products_id = '1'



回答2:


Wouldn't

SELECT products_id
FROM products
WHERE master_model_num = (SELECT model_num 
                          FROM products 
                          WHERE products_id = 1)

make more sense in this case? By having AND p.products_id='1' on the end of your query, you're guaranteeing that you'll only get one record back.




回答3:


Try this

SELECT 
  p.products_id 
 FROM 
   products p 
 INNER JOIN 
   products pp 
 ON 
   pp.products_master_model = p.products_model



回答4:


SELECT p.products_id FROM products p,products pp where p.model_num=pp.master_model_num and p.products_id='1' 


来源:https://stackoverflow.com/questions/8743960/how-to-write-this-self-join-query-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!