【问题标题】:MySQL Many-to-One relationshipMySQL 多对一关系
【发布时间】:2011-04-08 13:11:38
【问题描述】:

我很难掌握这个。

我有一个包含 hosts 的表格,每个都有十几行左右,还有一个带有 points 的表格,它实际上是一个包含有关主机的时间线信息的表格。

主机有很多点,随着时间的推移,这些点可以转化为主机条件的时间线。

如何将其转换为将 x points 与其各自的 host 分组的 SQL 查询?

示例:

Host: 
    id:1
    address: 123.456.7.8
    name: FooBar
    pickles: The good kind
    timeline:
        Point:
            host_id:1
            timestamp: 123456
            parameter: 123
        Point:
            host_id:1
            timestamp: 123456
            paramter:456

重要提示:我还想限制此时间轴列中的条目数。

我已经为此研究了很长时间,希望能得到一些帮助。

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

    你可以像这样子查询

    SELECT h.*, (SELECT COUNT(*) FROM points WHERE host = h.host) as points FROM hosts h
    

    【讨论】:

      【解决方案2】:

      看看你的例子

          select id, address, name, pickles,timestamp,parameter from host
       left join timeline on host.id = timeline.host_id 
      order by host.id
      

      但是,如果主机可能出现多次,我希望看到一个示例,您作为人类已经从示例数据中找出如何匹配它们

      【讨论】:

        【解决方案3】:

        select * from hosts right join timeline where host.id = timeline.host_id

        将返回所有点,主机信息在同一行。

        可以使用 GROUP BY 子句和 COUNT 函数按 host_id 聚合,得到点数:

        select count(host_id), hosts.id from hosts right join timeline where host.id = timeline.host_id group by host.id

        【讨论】:

          猜你喜欢
          • 2014-06-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-16
          • 1970-01-01
          • 2014-12-11
          • 2011-04-05
          • 1970-01-01
          相关资源
          最近更新 更多