如何通过join从两个表中获取数据

时间:2016-10-10 08:10:30

标签: php mysql join

表1: Main_Family_Member

ID | Name
1  | Mahesh
2  | Rahul
3  | Jay

表2: Family_Members

ID | MainMember | Name
1  | 1          | 'Arun'
2  | 1          | 'Nitin'
3  | 2          | 'Pratik'

想要结果

Name
Mahesh
Arun
Nitin
Rahul
Pratik

5 个答案:

答案 0 :(得分:2)

您可以通过执行两个表中的UNION ALL以及正确的排序来实现此目的。请注意,有必要将两个连接的表联合起来,因为我们需要知道一个主要的家庭成员是否有任何成员。如果他没有任何成员,您的样本输出意味着您根本不想显示该主要家庭成员。

SELECT t.Name
FROM
(
    SELECT DISTINCT t1.ID, t1.Name, 0 AS position
    FROM
    (
        SELECT t1.ID, t1.Name
        FROM Main_Family_Member t1
        INNER JOIN Family_Members t2
            ON t1.ID = t2.MainMember
        WHERE t2.ID IS NOT NULL
    ) t1
    UNION ALL
    SELECT t2.ID, t2.Name, 1 AS position
    FROM
    (
        SELECT t2.MainMember AS ID, t2.Name
        FROM Main_Family_Member t1
        INNER JOIN Family_Members t2
            ON t1.ID = t2.MainMember
        WHERE t2.ID IS NOT NULL
    ) t2
    ORDER BY ID, position, Name
) t

在这里演示:

SQLFiddle

答案 1 :(得分:0)

SELECT Main_Family_Member.Name, Family_Members.Name
FROM Main_Family_Member
INNER JOIN Family_Members
ON Main_Family_Member.ID = Main_Family_Member.MainMember;

答案 2 :(得分:0)

SELECT Main_Family_Member.Name,Family_Members.Name 来自Main_Family_Member INNER JOIN Family_Members ON Main_Family_Member.ID = Main_Family_Member.MainMember;

答案 3 :(得分:0)

您需要在两张桌子上执行INNER JOIN。这将返回第一个表中满足条件的所有行以及第二个表上与唯一字段上的第一个表连接的所有行。 SELECT Main_Family_Member.Name , Family_Members.Name FROM Main_Family_Member INNER JOIN Family_Members ON Main_Family_Member.ID = Family_Members.MainMember WHERE Main_Family_Member.ID = 1 OR Main_Family_Member.ID = 2

答案 4 :(得分:-1)

SELECT Main_Family_Member.Name,Family_Members.Name FROM Main_Family_Member 
INNER JOIN Family_Members ON Main_Family_Member.ID=Family_Members.MainMember