I'm having a hard time grasping this one.
I have a table with hosts , each with a dozen or so rows, and a table with points , which is actually a table with timeline information about a host.
A host has many points, which can be translated to a timeline on that host's conditions over time.
How can I translate that into an SQL query that groups x points with their respective host ?
Example:
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
Important: I also want to limit the number of entries in this timeline column.
I've been grinding my gears about this one for quite some time now, and I'd appreciate some help.
您可以执行类似的子查询
SELECT h.*, (SELECT COUNT(*) FROM points WHERE host = h.host) as points FROM hosts h
Looking at your example something like
select id, address, name, pickles,timestamp,parameter from host
left join timeline on host.id = timeline.host_id
order by host.id
However, if a host can have multiple occurances, I would want to see an example where you as a human had worked out from example data how to match them
select * from hosts right join timeline where host.id = timeline.host_id
Will return all points, with host information on the same row.
You can use the GROUP BY clause and COUNT functions to aggregate by the host_id and get the number of points:
select count(host_id), hosts.id from hosts right join timeline where host.id = timeline.host_id group by host.id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.