MySQL SELECT与

时间:2015-10-05 15:39:04

标签: mysql

我的数据库中有一些疯狂的结构,其中用户和orgniations在同一个表中(例如下面的例子)

他们都与PARENTID和MEMBERID联系在一起,我需要得到的是: GET name全部"人" ,他们的父母MEMBERID以及name

结果应如下所示:

UserName1 | DHAD781  | OrgName1

表格示例:

以下是db的示例:

    -------*/*------------*/*------------*/*------------*/*------------*/*------------
    MEMBERID      level          name           kind         status      PARENTID
    -------*/*------------*/*------------*/*------------*/*----------*/*------------
    EMD123F |     2        |   OrgName1   |     Org      |            |  rootID
    ---------------------------------------------------------------------------------
    DHAD781 |     3        |   UserName1  |    Person    |   active   |  EMD123F 
    ---------------------------------------------------------------------------------
    7AJIZU7 |     3        |   UserName2  |    Person    |   active   |  EMD123F 
    ---------------------------------------------------------------------------------
    DME123F |     2        |   OrgName2   |     Org      |            |  rootID
    ---------------------------------------------------------------------------------
    TT5451AL|     3        |   UserName3  |    Person    |   active   |  DME123F 
    ---------------------------------------------------------------------------------
    RRMI7481|     2        |   OrgName3   |     Org      |            |  rootID
    ---------------------------------------------------------------------------------
    PPUNSAD9|     2        |   OrgName4   |     Org      |            |  rootID
    ---------------------------------------------------------------------------------
    GJASDNZB|     3        |   UserName4  |    Person    |  inactive  |  PPUNSAD9
    ---------------------------------------------------------------------------------
    KJNSCZM7|     2        |   OrgName5   |     Org      |            |  rootID
    ---------------------------------------------------------------------------------
    1UZGOPAS|     3        |   UserName5  |    Person    |   deleted  |  KJNSCZM7
    ---------------------------------------------------------------------------------

我做了什么尝试:

SELECT t1.NAME, t1.MEMBERID 
    FROM roles t1 
    inner join roles t2 on t2.PARENTID = t1.MEMBERID
    WHERE t1.kind= 'Person'

我从这个查询中得到了什么: 找到0个结果

1 个答案:

答案 0 :(得分:1)

似乎是相反的方式:

SELECT persons.NAME, persons.MEMBERID, orgs.NAME, orgs.MEMBERID
    FROM roles persons 
    INNER JOIN roles orgs on persons.PARENTID = orgs.MEMBERID
    WHERE persons.kind = 'Person'

此外,选择显式别名会使查询更具可读性(并且更不容易出错:))