我有这个数据库结构:
sites
id | name
1 | Site 1
2 | Site 2
locations
id | city
23 | Baltimore
24 | Annapolis
people
id | name
45 | John
46 | Sue
sites_meta
id | site_id | meta_name | meta_value
1 | 1 | local | 23
2 | 1 | person | 45
3 | 2 | local | 24
4 | 2 | person | 46
因此,如您所见,站点 1 (id 1) 位于巴尔的摩并与 John 关联,站点 2 (id 2) 位于安纳波利斯并与 Sue 关联。
我需要找出一个可以返回的聪明的sql语句
id | name | id | city | id | name
1 | Site 1 | 23 | Baltimore | 45 | John
2 | Site 2 | 24 | Annapolis | 46 | Sue
如果有人能帮助我,我将非常感激。我已经尝试了 select 语句的几种组合,但我一直坚持使用sites_meta 表中的两个值。
最佳答案
select
s.id as siteId,
s.name as siteName,
max(l.id) as locationId,
max(l.city) as city,
max(p.id) as personId,
max(p.name) as personName
from
sites_meta sm
join sites s on s.id = sm.site_id
left join locations l on l.id = sm.meta_value and sm.meta_name = 'local'
left join people p on p.id = sm.meta_value and sm.meta_name = 'person'
group by
s.id,
s.name
你可能可以想象 this kind of "meta" table might become a pain ...尤其是当添加更多项目时。
相反,您可以考虑将其替换为两个新表:sites_locations
和 sites_people
。
关于mysql - 使用 meta_table 连接 4 个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9437048/