简体   繁体   English

如何将2个mysql查询与1个表合并为一个

[英]How to combine 2 mysql queries to 1 table into one

I have one table, example 我有一张桌子,例子

catid | parentcatid | dirname
  4   |      0      | mobiles 
 243  |      4      | Nokia

When I get catid = 243 I need to take with mysql_query (catid=parentcatid) 当我得到catid = 243我需要使用mysql_query (catid=parentcatid)

243 | mobiles | Nokia

I can first select catid , parentcatid , and dirname where id=243 and then select the same where parentcatid = catid , but 我可以先选择catidparentcatiddirname ,其中id=243 ,然后在parentcatid = catid选择相同的,但是

How to make this single query ? 如何进行这个单一查询?

JOIN the table twice: JOIN桌子两次:

SELECT
  t2.catid, t1.dirname 'dirname', t2.dirname 'parentname'
FROM Tablename t1
INNER JOIN Tablename t2 ON t1.catid = t2.parentcatid
WHERE t2.catid = 243;

SQL Fiddle Demo SQL小提琴演示

This will give you: 这会给你:

| CATID | DIRNAME | PARENTNAME |
--------------------------------
|   243 | mobiles |      Nokia |

Use a self-join: 使用自联接:

SELECT parent.catid, parent.dirname
FROM yourtable AS parent
LEFT JOIN yourtable AS child ON (child.parentcatid = parent.catid)
WHERE child.catid = 243

The literal answer to your question is to use a self-join (as Marc B suggests). 你的问题的字面答案是使用自我加入(如Marc B所建议的那样)。

Reading between the lines, I'm assuming that you don't know how deep your hierarchy is going to be in advance - that makes the self join less useful, because if you have to continue to join to get deeper levels of the tree, and you probably need to user outer joins if not all parts of the tree go to the same depth. 在线之间阅读,我假设您不知道您的层次结构将提前多深 - 这使得自联接不那么有用,因为如果您必须继续加入以获得更深层次的树,如果不是树的所有部分都达到相同的深度,你可能需要使用外连接。

The alternative approaches - much more complex, and only do this if my assumption is true - is to use a recursive function , or to represent your data as a nested set . 替代方法 - 更复杂,只有在我的假设成立时才这样做 - 是使用递归函数 ,或者将数据表示为嵌套集

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

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