0

I have two imaginary tables:

1. People

id, age
1, 25

2. Names

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

How can I join the two tables so I'd get this result:

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

4 回答 4

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

否则,如果您在 column 上有未知值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;
于 2013-11-03T12:28:06.070 回答
0
SELECT p.id, p.age, n.first, n.last
FROM People p
JOIN Names n 
ON p.id = n.people_id;
于 2013-11-03T12:33:56.937 回答
0

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

于 2013-11-03T12:28:58.053 回答
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 
于 2013-11-03T12:29:47.363 回答