[英]How to use join in my case Postgres query ?
i am trying to get product's name
and categ_id
. 我正在尝试获取产品的
name
和categ_id
。 I have two tables that are, 我有两张桌子,
product_template
categ_id name
7 Nokia classic
7 Nokia lumia
8 samsung s3
6 huawai
this table have product
that i want to get, 这张桌子有我想要的
product
,
product_category
id name parent_id
6 phones 3
7 nokia 6
8 samsung 6
this table shows that which product is under phone > nokia
and phone > samsung
or product can be directly under phone as shown under, 此表显示哪个产品在
phone > nokia
和phone > samsung
或产品可以直接在手机下如下所示,
like, 喜欢,
phones > huawai
phones > nokia > Nokia classic
phones > nokia > Nokia lumia
phones > samsung > samsung s3
query i am using is, 我正在使用的查询是,
select pt.categ_id,pt.name from product_template pt inner join product_category pc on
pt.categ_id=pc.id where pc.parent_id='6'
it is showing all products except huawai
??? 它显示除
huawai
以外的所有产品???
query should run like that it can get products that are under phone
directly and under this way phone > nokia > Nokia Classic
查询应该运行,因为它可以直接获得
phone
下的产品,并通过这种方式phone > nokia > Nokia Classic
Thanks in advance for your suggestions. 提前感谢您的建议。
If you want to fetch only the templates under a category, and the templates under that category's children categories, use that query: 如果您只想获取类别下的模板以及该类别的子类别下的模板,请使用该查询:
select pt.categ_id, pt.name
from product_template pt
inner join product_category pc on pt.categ_id = pc.id
where '6' in (pc.id, pc.parent_id)
But that selects only templates within 1 level range of the selected category. 但是,它仅选择所选类别的1个级别范围内的模板。 If you want to select all descendant categories' templates, you can use the recursive common table expression :
如果要选择所有后代类别的模板,可以使用递归公用表表达式 :
with recursive rpc(id) AS (
select '3'::int
union all
select id
from product_category pc
where pc.parent_id = rpc.id
)
select pt.categ_id, pt.name
from product_template pt
inner join rpc on pt.categ_id = rpc.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.