我经历过一些工作,我经常看到这样的数据库:
Column_Values + —— + ————– ————– + + | id | field_id |标签| …
条件聚合应该做的伎俩:
SELECT u.id, MAX(CASE WHEN cv.field_id = 'first_name' THEN m.value END) first_name, MAX(CASE WHEN cv.field_id = 'last_name' THEN m.value END) last_name FROM user u INNER JOIN mapping m ON m.user_id = u.id INNER JOIN Column_Values cv ON cv.id = m.field_id GROUP BY u.id
注意:如果您需要的只是用户ID及其名字和姓氏,那么您不需要引入 user 表。只是:
user
SELECT m.user_id, MAX(CASE WHEN cv.field_id = 'first_name' THEN m.value END) first_name, MAX(CASE WHEN cv.field_id = 'last_name' THEN m.value END) last_name FROM mapping m ON INNER JOIN Column_Values cv ON cv.id = m.field_id GROUP BY m.user_id
试试这个
select User_ID, max(FirstName) FirstName, max(LastName) LastName from ( select User_ID, case when c.Field_Id= 'first_name' then Value end as FirstName, case when c.Field_Id = 'last_name' then Value end as LastName from Column_Values c inner join MappingTable m on c.Id = m.FieldId ) t group by User_ID