我遇到了mysql查询的问题。我想拥有一个父级的多级子ID。因此,如果父ID为18,那么我想让子ID为18,如果有任何子级别,那么我也希望它们基于类型id
我的表格结构如下 - 页面表
id title parent_id type_id
18 About Us 0 4
19 Child 1 18 6
20 child 2 18 7
21 child 3 18 1
22 sub child 1 21 14
23 sub child 2 21 14
24 sub child 3 21 15
第二个表 - page_types
id typetitle
6 one column
7 two column
14 slider
我想要的输出应该是
id title parent_id type_id typetitle
19 Child 1 18 6 one column
20 child 2 18 7 two column
22 sub child 1 21 14 slider
23 sub child 2 21 14 slider
我的查询是
SELECT
p.id AS childid,
p.title AS ptitle,
pt.typetitle as page_type_title
FROM pages AS p,page_types as pt
where p.type_id in (6,7,14) and p.parent_id=18 and p.type_id = pt.id
但我只得到2行(19和20)但不是22行和23行。
答案 0 :(得分:1)
您似乎想要树的叶子而不是中间节点。试着这样做:
SELECT p.id AS childid, p.title as ptitle, pt.typetitle as page_type_title
FROM pages p join
page_types pt
ON p.type_id = pt.id
WHERE p.type_id in (6, 7, 14) and
NOT EXISTS (SELECT 1 FROM pages p2 WHERE p2.parent_id = p.id);
Here是一个SQL小提琴,显示正在运行的查询。
答案 1 :(得分:0)
我认为这是你搜索的内容:
SELECT * FROM pages AS p INNER JOIN types AS t ON p.type_id = t.id WHERE p.type_id in (6,7,14) and p.parent_id <> 0