我在构建SQL语句时需要一些帮助。我有两张桌子。
categories
和name
的表parent
,其中parent
引用其自身的ID。 例如:
ID name parent
-------------------------
1 Fruit Null
2 Banana 1
3 Apple 1
Fooddiary
的表examplecol1, examplecol2, "categorie
,其中categorie
引用categories
的ID现在,我想获取所有Fooddiary
条目,其中examplecol1 == "test"
的格式如下:
Categorie Subcategorie examplecol1 examplecol2
---------------------------------------------------------
Fruit Banana test a
Fruit Banana test b
Fruit Apple test a
我尝试了类似的加入:
Select
categories.name, categories.parent,
examplecol1, examplecol2
from
Fooddiary
join
categories on categorie = categories.id
where
examplecol1=="test";
这有效,但在我的结果列Categorie
中有父ID而不是名称。所以我要寻找的是这样的:
Select
categories.name, categories.parent.name,
examplecol1, examplecol2
from
Fooddiary
join
categories on categorie = categories.id
where
examplecol1 == "test";
有人可以帮助解决这个问题吗?
您在寻找这个吗?
select cat.NAME, cat.PARENT, parents.NAME, fd.EXAMPLECOL1, fd.EXAMPLECOL2
from FOODDIARY fd
inner join CATEGORIES cat on fd.CATEGORIE = cat.ID
left join CATEGORIES parents on cat.PARENT = parents.ID
where fd.EXAMPLECOL1 = 'test'