MySQL将两个表连接成一个

时间:2013-11-03 12:25:31

标签: mysql join

我有两个虚构的表格:

1。 人

id, age
1, 25

2。 名称

id, people_id, type, value
1, 1, 'first', 'John'
2, 1, 'last', 'Doe'

我如何加入这两个表,以便得到这个结果:

id, age, first, last
1, 25, 'John', 'Doe'

4 个答案:

答案 0 :(得分:3)

SELECT  a.ID,
        a.Age,
        MAX(CASE WHEN b.type = 'first' THEN b.Value END) `First`,
        MAX(CASE WHEN b.type = 'last' THEN b.Value END) `Last`
FROM    People a
        LEFT JOIN Names b
            ON a.ID = b.people_id
GROUP   BY a.ID, a.Age

否则,如果列type上的值不明,则更喜欢动态语句。

SET @sql = NULL;

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('MAX(CASE WHEN b.type = ''',
               type,
               ''' THEN value ELSE NULL END) AS ',
               CONCAT('`', type, '`')
               )) INTO @sql
FROM Names;

SET @sql = CONCAT('SELECT  a.ID,
                            a.Age, ', @sql , '
                    FROM    People a
                            LEFT JOIN Names b
                                ON a.ID = b.people_id
                    GROUP   BY a.ID, a.Age');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

答案 1 :(得分:0)

您正在寻找有关如何连接来自不同表的数据的一般信息。它被称为内连接。 可以找到参考here

答案 2 :(得分:0)

希望它可以帮到你,

方法:1

 select p.id, p.age, n.type as first, n.value as last from People as p, Names as n where p.id = n.people_id

方法:2

 select p.id, p.age, n.type as first, n.value as last from People as p LEFT JOIN Names as n ON p.id = n.people_id 

答案 3 :(得分:0)

SELECT p.id, p.age, n.first, n.last
FROM People p
JOIN Names n 
ON p.id = n.people_id;