Delving into some complex SQL here. I want to create a view/virtual table.
I have an object table. Which looks something like this (all values are int)
| id | parent_id | foreign_key | start_date | end_date |
CREATE TABLE objects (
id int AUTO_INCREMENT PRIMARY KEY,
parent_id INT(11),
foreign_key INT(11),
start_date INT(11),
end_date INT(11)
);
INSERT INTO objects
VALUES
(1, 0, 1, 1638930577, 1638930578),
(2, 1, 1, 1638930578, 1638930578),
(3, 2, 1, 1638930578, 1638930578),
(4, 0, 2, 1638930576, 1638930578),
(5, 4, 2, 1638930578, 1638930578),
(6, 5, 2, 1638930578, 1638930578),
(7, 0, 1, 1638930574, 1638930578),
(8, 7, 1, 1638930578, 1638930578),
(9, 7, 1, 1638930578, 1638930579)
I want to create a view that looks like
| id | start_date | end_date | number_of_objects |
I've never used SQL views before, and would be ideal in my situation rather than writing code. Is this possible? My main qualm is that when I do this in code, I need to give it an object_id to start, really not sure how to just get a group of objects with the same parent id that isn't 0.
Thank you
P.S Using MySQL/Maria most recent version but dialect probably isn't super important.
SQL Fiddle: http://sqlfiddle.com/#!9/429570/1
The return result from the new view, provided from the schedule should look like
| id | foreign_key | start_date | end_date | number_of_objects |
|---|---|---|---|---|
| 1 | 1 | 1638930577 | 1638930578 | 3 |
| 2 | 2 | 1638930576 | 1638930578 | 3 |
| 3 | 1 | 1638930574 | 1638930579 | 3 |
The return result should be built something like this:
- Gets all objects with parent = 0.
- For each of those objects, get all the child objects (WHERE parent = parent.id)
- The parent and its children consist of one
objectGroup. The item in the new view consists of- id = an autogenerated id. Probably optional but feels good to have.
- foreign_key = the same foreign key value as all objects in the objectGroup should have.
- start_date - min() of all start dates in the objectGroup.
- end_date - max() of all end dates in the objectGroup.
- number_of_objects - count() of all objects in the objectGroup