问题
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