SQL: Get latest entries from history table - mysql

I have 3 tables
person (id, name)
area (id, number)
history (id, person_id, area_id, type, datetime)
In this tables I store the info which person had which area at a specific time. It is like a salesman travels in an area for a while and then he gets another area. He can also have multiple areas at a time.
history type = 'I' for CheckIn or 'O' for Checkout.
Example:
id person_id area_id type datetime
1 2 5 'O' '2011-12-01'
2 2 5 'I' '2011-12-31'
A person started traveling in area 5 at 2011-12-01 and gave it back on 2011-12-31.
Now I want to have a list of all the areas all persons have right now.
person1.name, area1.number, area2.number, area6.name
person2.name, area5.number, area9.number
....
The output could be like this too (it doesn't matter):
person1.name, area1.number
person1.name, area2.number
person1.name, area6.number
person2.name, area5.number
....
How can I do that?

This question is, indeed, quite tricky. You need a list of the entries in history where, for a given user and area, there is an 'O' record with no subsequent 'I' record. Working with just the history table, that translates to:
SELECT ho.person_id, ho.area_id, ho.type, MAX(ho.datetime)
FROM History AS ho
WHERE ho.type = 'O'
AND NOT EXISTS(SELECT *
FROM History AS hi
WHERE hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
)
GROUP BY ho.person_id, ho.area_id, ho.type;
Then, since you're really only after the person's name and the area's number (though why the area number can't be the same as its ID I am not sure), you need to adapt slightly, joining with the extra two tables:
SELECT p.name, a.number
FROM History AS ho
JOIN Person AS p ON ho.person_id = p.id
JOIN Area AS a ON ho.area_id = a.id
WHERE ho.type = 'O'
AND NOT EXISTS(SELECT *
FROM History AS hi
WHERE hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
);
The NOT EXISTS clause is a correlated sub-query; that tends to be inefficient. You might be able to recast it as a LEFT OUTER JOIN with appropriate join and filter conditions:
SELECT p.name, a.number
FROM History AS ho
JOIN Person AS p ON ho.person_id = p.id
JOIN Area AS a ON ho.area_id = a.id
LEFT OUTER JOIN History AS hi
ON hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
WHERE ho.type = 'O'
AND hi.person_id IS NULL;
All SQL unverified.

You're looking for results where each row may have a different number of columns? I think you may want to look into GROUP_CONCAT()
SELECT p.`id`, GROUP_CONCAT(a.`number`, ',') AS `areas` FROM `person` a LEFT JOIN `history` h ON h.`person_id` = p.`id` LEFT JOIN `area` a ON a.`id` = h.`area_id`
I haven't tested this query, but I have used group concat in similar ways before. Naturally, you will want to tailor this to fit your needs. Of course, group concat will return a string so it will require post processing to use the data.
EDIT I thikn your question has been edited since I began responding. My query does not really fit your request anymore...

Try this:
select *
from person p
inner join history h on h.person_id = p.id
left outer join history h2 on h2.person_id = p.id and h2.area_id = h.area_id and h2.type = 'O'
inner join areas on a.id = h.area_id
where h2.person_id is null and h.type = 'I'

Related

MySQL, select, comparing values from 2 tables

in my database I want to select every construction_manual
where storage_room.quantity > component.quantity
But when I use:
SELECT construction_manual.name
FROM construction_manual cm, construction_manual_component cmc, component, storage_room
WHERE cm.ID = cmc.construction_manual_ID
AND cmc.component_ID = component.ID
AND component.storage_room_ID = storage_room.ID
AND storage_room.quantity > component.quantity
It will select every construction_manual.name as long as the first component in the storage_room has enough quantity.
So let's say...
construction_manual.1 needs
component.A -> quantity 5
component.B -> quantity 10
and in the storage room there is:
component.A -> quantity 6
component.B -> quantity 0
Although there is not enough in the storage room, construction_manual.1 will be selected. How do I select only those construction_manuals where there are enough components in the storage_room?
edit:
In my 4 tables are the following datasets. I will get the following result when I use the query mentioned above:database . But I should not be able to construct a table because there are not enough wooden_plates (wooden planks and not wooden plates ofc...ups)
I think what you want to ask is to ignore or exclude any construction manual that does not have enough components to satisfy a build. If that's the case you can do something like the below (a left join would also do it):
select distinct cm.name as construction_manual
from construction_manual cm
join construction_manual_component cmc
on cmc.construction_manual_ID = cm.ID
join component c
on c.ID = cmc.component_ID
join storage_room sr
on sr.ID = c.storage_room_ID
where sr.quantity > c.quantity
and cm.ID not in (select cm.ID
from construction_manual cm
join construction_manual_component cmc
on cmc.construction_manual_ID = cm.ID
join component c
on c.ID = cmc.component_ID
join storage_room sr
on sr.ID = c.storage_room_ID
where sr.quantity < c.quantity);

I want to go down further into query, but not sure how

MySQL Table Diagram:
My query this far:
SELECT tblcourses.CourseStandard,
tblcourses.CourseID,
tblcourses.CourseRef,
tblcourses.CourseStandard,
tblcourses.CourseName,
tblcourses.CourseDuration,
tblcourses.NQFLevel,
tblcourses.CoursePrice,
tblcoursestartdates.StartDate
FROM etcgroup.tblcoursestartdates tblcoursestartdates
INNER JOIN etcgroup.tblcourses tblcourses
ON (tblcoursestartdates.CourseID = tblcourses.CourseID)
WHERE tblcoursestartdates.StartDate >= Now()
If you look at the diagram you will see I have a 3rd table. The query above works fine. It display all the data as it should.
I want to show all the courses and their respective dates excluding those that the student is already booked for. Keep in mind that there can be 20 start dates for 1 course. This is why I am only choosing dates >= Now().
I want to make sure that a student does not get double booked. Yes I can do it afterwards. Beep student already booked BUT if I can have it now show the course dates that the student already booked then great. Any suggestions?
This is pretty straightforward. Presumably you know the StudentID you'd like to see. Do a left join to the bookings table and select the mismatches.
SELECT tblcourses.CourseStandard,
tblcourses.CourseID,
tblcourses.CourseRef,
tblcourses.CourseStandard,
tblcourses.CourseName,
tblcourses.CourseDuration,
tblcourses.NQFLevel,
tblcourses.CoursePrice,
tblcoursestartdates.StartDate
FROM etcgroup.tblcoursestartdates tblcoursestartdates
INNER JOIN etcgroup.tblcourses tblcourses
ON tblcoursestartdates.CourseID = tblcourses.CourseID
AND tblcoursestartdates.StartDate >= Now()
LEFT JOIN tblbookings
ON tblbookings.CourseId = tblcourses.CourseId
AND tblbookings.StudentId = <<<the student ID in question >>>
WHERE tblbookings.BookingID IS NULL
The trick here is the LEFT JOIN ... IS NULL pattern. It eliminates the rows where the ON condition of the LEFT JOIN hit, leaving only the ones where it missed.
Do a left join to tblBookings on courseID where the bookingID is null (there are no matches). You'll have to provide the studentID as a parameter to the query.
SELECT DISTINCT c.CourseStandard,
c.CourseID,
c.CourseRef,
c.CourseStandard,
c.CourseName,
c.CourseDuration,
c.NQFLevel,
c.CoursePrice,
d.StartDate
FROM etcgroup.tblcoursestartdates d
INNER JOIN etcgroup.tblcourses c ON d.CourseID = c.CourseID
LEFT JOIN etcgroup.tblBookings b on c.CourseID = b.CourseID and b.StudentID = #StudentID
WHERE d.StartDate >= Now() and b.bookingID is null
Use NOT EXISTS or NOT IN to find the courses a student has already booked:
SELECT
c.CourseStandard,
c.CourseID,
c.CourseRef,
c.CourseStandard,
c.CourseName,
c.CourseDuration,
c.NQFLevel,
c.CoursePrice,
csd.StartDate
FROM etcgroup.tblcourses c
INNER JOIN etcgroup.tblcoursestartdates csd ON csd.CourseID = tblcourses.CourseID
WHERE csd.StartDate >= Now()
AND c.CourseID NOT IN
(
SELECT CourseID
FROM tblbookings
WHERE StudentID = 12345
);

What is wrong with this MySQL query (formatting left join)?

I have a query as follows:
SELECT
staff_names.staff_ID AS sid
staff_names.name AS name,
staff_names.rec_type AS rec_type,
prod_staff.specialized AS specialized,
compspec.name AS compspec_name
FROM staff_names JOIN prod_staff USING (staff_ID)
LEFT JOIN (prod_staff_compspec JOIN company_list USING (comp_ID)) compspec
USING (prod_ID, staff_ID, role_ID)
WHERE prod_staff.role_ID = 2
AND prod_staff.prod_ID = 27
AND prod_staff.asst = 'n'
AND episode IS NOT NULL
ORDER BY name
Running this as-is says there's an error near the 'compspec' alias. Removing that and changing 'compspec' to 'company_list' in the SELECT clause returns no rows, even though it should return 1 with the given values. The left join seems to be the problem, but I don't how it should be formatted.
The prod_staff table has prod_ID, staff_ID and role_ID fields. prod_staff_compspec has these and a comp_ID field. prod_staff may or may not have a matching prod_staff_compspec row, but prod_staff_compspec always has a matching company_list row.
What I want to do is retrieve a list of all staff names associated with a given role_ID and prod_ID in the prod_staff table, as well as a company name from the company_list table, if a link to such exists in the prod_staff_compspec table (only a small minority have one).
Switched to ON to define the table relations. LEFT JOIN (prod_staff_compspec JOIN company_list USING (comp_ID)) compspec is switched to 2 left join.
select a.staff_id sid, a.name, a.rec_type, b.specialized, d.name compspec_name
from staff_names a
join prod_staff b on a.staff_id = b.staff_id
left join prod_staff_compspec c on b.prod_id = c.prod_id and b.staff_id = c.staff_id and b.role_id = c.role_id
left join company_list d on c.comp_id = d.comp_id
where b.role_id = 2 and b.prod_id = 27 and b.asst = 'n' and episode is not null
order by a.name;

Where clause in Query

My query looks like this. Suppose it was run well.im confused the last part of the Where clause.Can i write that from two different table?..how can i write it, cause i want to display those staff who a Active from that date range.
select d.Division,a.FirstName,
(select count(h.id) from Department h
inner join institution i on d.institution_id = i_Id
----
----
where i.institution_id =d.Id and h. date between #startDate and #endDate) as test
from Division d, inmate a
where d.Active = 1 and a.Active = 1
edited
i have edit my query and the final looks like this..
select d.DivisionName,a.FirstName, (select count(h.id) from InHistory h inner join Institution i on h.Institution_id = i.Id inner join InType it on h.InType_id = it.Id inner join mate a on h.mate_id = a.Id where i.InstitutionRegion_id = d.Id and it.InTypeName like '%Staff%' and h.AdmissionDate between '18/02/2013' and '18/02/2013') as Admission from Division d, mate a where d.Active= 1 and a.Active =1
Yes, you can give comparison between any number of tables in where clause provided you are giving valid conditions inside your where clause. I think you should refer SQL JOINS
You can add as many as you want clauses inside the WHERE from your SQL query..
see an example
SELECT *
FROM employee inner join department on
employee.DepartmentID = department.DepartmentID;
WHERE
employee.active = TRUE AND
department.group = 3
http://en.wikipedia.org/wiki/Join_(SQL)#Inner_join

What I need to add to this SQL instruction to filter some items?

What I want is to filter (not get) offers that appear in this new table, which we use like a black list (i.e., for the domain X we dont want offers with origin Y).
TABLE: black_list_deals
COLUMNS: id
domain_id (we save here an id from the table "domain")
origin_offer (we save here a value from deal, the field deal_source_id)
Until now I was using this instruction, but now I need to add the new behaviour to filter depending of the blacklist table to filter these offers.
SELECT
a.lat,
a.lon,
a.id,
a.image,
a.link,
a.deal_source_id,
a.date_posted,
a.date_expires,
a.tags_external,
a.tags_internal,
a.gender,
a.price,
a.discount,
a.areas,
a.hits,
a.bias,
a.collection_type,
a.uniqueness,
a.date_posted = current_date AS today,
DATEDIFF( a.date_expires, current_date) AS days_remaining,
a.collection_type,
b.id AS area_id,
b.area,
a.image_thumb,
c.source_img_email,
c.source_price,
c.source_img_sm,
c.source_name,
c.frame,
a.date_posted = current_date AS today,
d.country,
d.region,
e.level1,
e.level2,
e.level3,
e.level4
FROM deal a
LEFT JOIN area b ON (a.areas = b.id)
LEFT JOIN deal_source c ON (a.deal_source_id = c.id)
LEFT JOIN deal_travel d ON (a.id = d.deal_id)
LEFT JOIN deal_travel_country e ON (d.country = e.id)
WHERE
a.validated = 'y' AND
a.date_posted = current_date AND
a.date_expires >= current_date AND
email_deal = '1'
Adding WHERE a.deal_source_id NOT IN (SELECT origin_offer FROM black_list_deals) to your WHERE clause should solve this.
I would add
SELECT
...
FROM deal a
...
LEFT JOIN black_list_deals bld ON (bld.origin_offer = a.deal_source_id)
...
WHERE
...
AND bld.id IS NULL
basically you will return only the data for which an entry in the black list is not found