mysql - 使用 meta_table 连接 4 个表

标签 mysql join

我有这个数据库结构:

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_locationssites_people

关于mysql - 使用 meta_table 连接 4 个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9437048/

相关文章:

php - MySQL 查询确实需要很长时间才能加载然后超时

mysql - 查询在 MYSQL 中有效,但在 MYSQLI 中无效

php - 为每个用户配置文件创建 PHP 分析

sql - PostgreSQL:加入另一个表的计数

mysql - SQL - 无法弄清楚如何连接三个表

php - 从 Mysqli 中获取 id

php - 如何从命令行运行 PHP

mysql - DELETE JOIN 出现问题

sql - PostgreSQL 选择通过多对多数据透视连接的表的多个列

sql - Ruby ActiveRecord 通过关联进行多重联接