从表中选择所有在其他表中可用

时间:2012-10-11 16:14:03

标签: mysql

Table ( members )
-----------------
ID  Full_Name   Recommended_By  Direction   Node
1   Name1            None   
2   Name2                  1       Left         (1)
3   Name3                  1       Right    (1)
4   Name4                  2       Left         (2)(1)
5   Name5                  3       Left         (3)(1)
6   Name6                  2       Left         (2)(1)
7   Name7                  3       Right    (3)(1)

我运行下面的脚本它只返回一个ID第一个ID(1),但我需要所有ID。

ID  Node    Left_Direction  Right_Direction Recommended_By
2   (1)     Name2                    1
3   (1)                     Name3        1
4   (2)(1)      Name4                    2
5   (3)(1)      Name5                    3
6   (2)(1)      Name6                    2
7   (3)(1)                      Name7        3


select a.ID,a.Node,
(case when (a.Direction = 'Left') then a.Full_Name else '' end) AS `Left_Direction`,
(case when (a.Direction = 'Right') then a.Full_Name else '' end) AS `Right_Direction`,
a.Recommended_By 


from 
members a
WHERE
CONCAT("'%(",a.ID,")%'") in ( SELECT b.Node From members b)

AND
a.Node IS NOT NULL or trim(a.Node) <> ''
GROUP BY a.ID

1 个答案:

答案 0 :(得分:0)

认为你要做的是使用LIKE进行表连接。

尝试这样的事情:

SELECT
    a.ID,a.Node,
    (case when (a.Direction = 'Left') then a.Full_Name else '' end) AS `Left_Direction`,
    (case when (a.Direction = 'Right') then a.Full_Name else '' end) AS `Right_Direction`,
    a.Recommended_By 
FROM members a
INNER JOIN members b ON a.Node LIKE CONCAT('%(',b.ID,')%');