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'
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;
SELECT p.id, p.age, n.first, n.last
FROM People p
JOIN Names n
ON p.id = n.people_id;
您正在寻找有关如何连接来自不同表的数据的一般信息。它被称为内连接。参考可以在这里找到。
希望对你有帮助
方法: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