简体   繁体   English

php&mysql查找父类别名称

[英]php&mysql find parent category name

I have problem about inner join, left join commands. 我有关于内部联接,左联接命令的问题。

My category table is: 我的类别表是:

ID  | parent | title
1   | 0      | First Category
2   | 1      | Other Category

I have list categorys and I want get parents category title at sql command. 我有列表类别,我想在sql命令中获取父母类别标题。

I have tried: 我努力了:

SELECT cat.ID, cat.title, cat2.title as parentcatname, cat.parent
FROM   categories cat INNER JOIN categories cat2 ON cat2.ID=cat.parent

But ıt's not working. 但是它不起作用。

You have to use LEFT JOIN to be able to pull all categories no matter have they parent category or not. 您必须使用LEFT JOIN才能拉出所有类别,无论它们是否为父类别。 INNER JOIN filters out all mismatches. INNER JOIN过滤掉所有不匹配项。

SELECT c.id, c.title, c.parent, p.title parent_title 
  FROM categories c LEFT JOIN categories p 
    ON c.parent = p.id

Output: 输出:

| ID |          TITLE | PARENT |   PARENT_TITLE |
-------------------------------------------------
|  1 | First Category |      0 |         (null) |
|  2 | Other Category |      1 | First Category |

Here is SQLFiddle demo 这是SQLFiddle演示

If you want to get all parent categories then try query 如果要获取所有父类别,请尝试查询

SELECT cat_id FROM categories WHERE parent=0;

If you want get parent category of a category 如果要获取某个类别的父类别

SELECT C.cat_id, P.title FROM categories C LEFT JOIN categories P ON P.parent=C.cat_id; 从类别C LEFT JOIN类别P ON P.parent = C.cat_id中选择C.cat_id,P.title;

I haven't tested above code but it should work fine. 我没有测试上面的代码,但它应该可以正常工作。

You can always debug your SQL by entering it into a validator (loads online), phpMyAdmin's SQL tab or a editor with SQL validation. 您始终可以通过将SQL输入到验证器(在线加载),phpMyAdmin的SQL选项卡或带有SQL验证的编辑器中来调试SQL。 It looks to me like you have a small typo near your categories table selection. 在我看来,您在类别表选择项附近有一个小错字。

Always dumb it down if your SQL isn't working. 如果您的SQL无法正常工作,请务必将其忽略。 Note that JOINs (inner, left, right, ect) are meant to join TWO or MORE tables. 请注意,JOIN(内部,左侧,右侧等)用于联接两个或更多表。

SELECT 
    one.ID, one.title, one.parent, one.title, one.parent, one.title
FROM 
    categories one 
LEFT JOIN 
    categories two
ON 
    one.parent = two.ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM