Selecting IDs from a MIN query that includes join - mysql

sorry about the title, very bad at titles!
I have these relevant tables:
Times
+--------+----------+-------------+------+---------+
| TimeID | PlayerID | MapCourseID | Mode | RunTime |
+--------+----------+-------------+------+---------+
Checkpoints
+--------------+--------+------------+---------+
| CheckpointID | TimeID | Checkpoint | RunTime |
+--------------+--------+------------+---------+
Maps
+-------+------+
| MapID | Name |
+-------+------+
MapCourses
+-----------+-------+--------+
| MapCourse | MapID | Course |
+-----------+-------+--------+
RunTime stores their "time" as an int
I have a query that selects the fastest times for a specific map MapID on all courses and all modes
SELECT MIN(Times.RunTime), MapCourses.Course, Times.Mode
FROM Times
INNER JOIN MapCourses ON MapCourses.MapCourseID=Times.MapCourseID
INNER JOIN Players ON Players.PlayerID=Times.PlayerID
WHERE Players.Cheater=0 AND MapCourses.MapID=%d
GROUP BY MapCourses.Course, Times.Mode;
Which works fine, but now I want to make another query that selects the checkpoints of the fastest times, since checkpoints are associated with a TimeID
I've tried doing something like this
SELECT * FROM Checkpoints
INNER JOIN (
SELECT
MIN(Times.RunTime),
MapCourses.Course,
Times.Mode,
MapCourses.MapID,
Players.SteamID32
FROM
Times
INNER JOIN MapCourses ON MapCourses.MapCourseID = Times.MapCourseID
INNER JOIN Players ON Players.PlayerID = Times.PlayerID
WHERE
Players.Cheater = 0
AND MapCourses.MapID = %d
GROUP BY
MapCourses.Course,
Times.Mode
) AS wrs ON Checkpoints.TimeID = wrs.TimeID
Also tried something like this:
SELECT
Checkpoints.RunTime,
Checkpoints.Checkpoint,
MapCourses.Course,
Times.Mode,
Times.TimeID,
Players.Alias
FROM
Checkpoints
INNER JOIN Times ON Times.TimeID = Checkpoints.TimeID
INNER JOIN MapCourses ON MapCourses.MapCourseID = Times.MapCourseID
INNER JOIN Players ON Players.PlayerID = Times.PlayerID
WHERE
Players.Cheater = 0
AND MapCourses.MapID = %d
AND Times.RunTime = (
SELECT
MIN(Times.RunTime)
FROM
Times
WHERE
Times.MapCourseID = MapCourses.MapCourseID
AND Mode = Times.Mode
)
Neither seem to really work, any help would be great, thanks!
Basically, if i'm working on map id 50, I already have a query that gets the fastest time on map id 50 for all modes & courses, the query i'm trying to build is a query that gets the checkpoints of the fastest times for every course and mode on map id 50

We could do something like this:
SELECT c.checkpointid
, c.timeid
, c.checkpoint
, c.runtime
, ...
FROM ( SELECT t.mapcourseid
, t.mode
, MIN(r.runtime) AS min_runtime
FROM Times r
JOIN Players p
ON p.playerid = r.playerid
AND p.cheater = 0
JOIN MapCourses s
ON s.mapcourseid = t.mapcourse_id
AND s.mapid = ?
GROUP
BY t.mapcourseid
, t.mode
) q
JOIN Times t
ON t.runtime = q.min_runtime
AND t.mapcourseid = q.mapcourseid
JOIN Checkpoints c
ON c.timeid = t.timeid
The trick here is using a query as an inline view. The result returned from the query inside the parens gets returned as a resultset, which is then used like a table by the outer query. MySQL calls it a "derived table".
In the outer SELECT list, we can include references to columns from q and t as well as c.
Note: If there are two or more rows from t that match the minimumn runtime (returned by q), the query will return all of the matching rows.
The specification is a bit unclear. The query in this answer satisfies one particular interpretation.

If I'm following this correctly, you want the shortest Checkpoints.TimeID for each Checkpoint in a similar format to the above?
SELECT MIN(Checkpoints.TimeID), MapCourses.Course, Checkpoints.Checkpoint, Times.Mode
FROM Checkpoints
INNER JOIN Times ON Checkpoints.TimeID=Times.TimeID
INNER JOIN MapCourses ON MapCourses.MapCourseID=Times.MapCourseID
INNER JOIN Players ON Players.PlayerID=Times.PlayerID
WHERE Players.Cheater=0 AND MapCourses.MapID=%d
GROUP BY MapCourses.Course, Checkpoints.Checkpoint, Times.Mode;
Obviously not having access to your Database I can't test this, but, seems to be what you're asking?
[edit]
Ahh, so you want to keep the min times, but would like to add checkpoints into the returned values:
SELECT MIN(Times.RunTime), MapCourses.Course, Checkpoints.Checkpoint, Times.Mode
FROM Times
INNER JOIN MapCourses ON MapCourses.MapCourseID=Times.MapCourseID
INNER JOIN Players ON Players.PlayerID=Times.PlayerID
INNER JOIN Checkpoints ON Checkpoints.TimeID=Times.TimeID
WHERE Players.Cheater=0 AND MapCourses.MapID=%d
GROUP BY MapCourses.Course, Checkpoints.Checkpoint, Times.Mode;
So this should return your fastest time, the map, checkpoints and then mode.

Related

Need count of transactional table based on other tables including zeros where there are no matches

I have four tables, three of which are pretty static: haul_types, dumpster_type_team (the dumpster_type_team has the many-to-many relationship between dumpster_types and teams), and users. The fourth table, hauls, has transactional data.
haul_types:
id
name
dumpster_type_team:
id
dumpster_type_id
team_id
users:
id
first_name
last_name
is_driver
team_id
hauls:
haul_type_id
haul_status_id
set_dumpster_type_id
completed_driver_id
team_id
I would like a query that has a combination of dumpster_types, haul_types, and drivers (users) and a count of the hauls they were involved in. In some cases, there should be a count of zero because some drivers haven't completed hauls for every haul_type / dumpster type combination.
Here's the query I have so far that seems to be behaving as if it is an inner join because the records are getting filtered to only show where there are matches:
SELECT
c.haul_type_id,
c.dumpster_type_id,
c.driver_id,
count(h.id) AS haul_count
FROM
hauls h
RIGHT JOIN ( SELECT DISTINCT
ht.id AS haul_type_id,
dtt.dumpster_type_id AS dumpster_type_id,
dtt.team_id AS team_id,
u.id AS driver_id
FROM
haul_types ht
CROSS JOIN dumpster_type_team dtt
CROSS JOIN users u
WHERE
u.team_id = dtt.team_id
AND u.is_driver = TRUE) c ON c.haul_type_id = h.haul_type_id
AND c.dumpster_type_id = h.set_dumpster_type_id
AND c.driver_id = h.completed_driver_id
AND c.team_id = h.team_id
WHERE
h.team_id = 9
AND h.haul_status_id = 3
AND h.completed_driver_id IS NOT NULL
GROUP BY
c.haul_type_id, c.dumpster_type_id, c.driver_id
When I run the subquery in isolation:
SELECT DISTINCT
ht.id AS haul_type_id,
dtt.dumpster_type_id AS dumpster_type_id,
dtt.team_id AS team_id,
u.id AS driver_id
FROM
haul_types ht
CROSS JOIN dumpster_type_team dtt
CROSS JOIN users u
WHERE
u.team_id = dtt.team_id
AND u.is_driver = TRUE
I get the results I want: a row for each permutation of haul_type, dumpster_type, driver_id, and team_id. However, when I run the entire query, I get filtered results despite the right join.
What I would like to have is the following:
If I have 4 haul_types: delivery, swap, live, pickup
and 2 dumpster_types: 10YD, 15YD
and 2 drivers: 1, 2
I would like a haul count for the combination of haul_type, dumpster_type, and driver. If there are no hauls matching the row, show 0:
Any help is appreciated. Thank you
The description of the question and the query seem to have little to do with each other. I don't know what a "pivot table" is supposed to be.
I would like a query that has a combination of dumpster_types, haul_types, and drivers (users) and a count of the hauls they were involved in.
This sounds like a cross join to generate the rows and then a left join/group by to calculate the results:
select d.dumpster_id, ht.haul_type_id, d.driver_id, count(h.driver_id)
from dumpster_types d cross join
haul_types ht cross join
drivers d left join
hauls h
on h.dumpster_id = d.dumpster_id and
h.haul_type_id = ht.haul_type_id and
h.driver_id = d.driver_id
group by d.dumpster_id, ht.haul_type_id, d.driver_id;
Running the query #GordonLinoff provided, exposed the issue I was facing - when applying a where clause on the top level query, the results were getting filtered to only matches. I moved the where clause to individual subqueries and now I am getting all expected results.
Not sure if this is the most efficient way to write it but it yields the correct results:
SELECT
d.dumpster_type_id,
ht.id AS haul_type_id,
u.id AS driver_id,
count(h.id) AS haul_count
FROM (
SELECT
dumpster_type_id,
team_id
FROM
dumpster_type_team
WHERE
team_id = 9) d
CROSS JOIN haul_types ht
CROSS JOIN (
SELECT
users.id
FROM
users
WHERE
users.is_driver = TRUE
AND users.team_id = 9) u
LEFT JOIN (
SELECT
id, set_dumpster_type_id, haul_type_id, completed_driver_id, team_id
FROM
hauls
WHERE
haul_status_id = 3
AND team_id = 9) h ON h.set_dumpster_type_id = d.dumpster_type_id
AND h.haul_type_id = ht.id
AND h.completed_driver_id = u.id
AND h.team_id = d.team_id
GROUP BY
d.dumpster_type_id,
ht.id,
u.id

SQL Query Count With JOIN

I've the following SQL Query which runs perfectly fine but now i want to calculate the count based on the following scenario:
SELECT d.vseverity, v.vulnstatus, v.vtitleid, d.vtitle
FROM vulnsummary v
JOIN project p ON v.projid = p.projid
AND v.stagename = p.currentstage
JOIN datasets d ON v.vtitleid = d.datasetid
The current Output is:
Now i want to show the count like this way:
High (Open) - 2
High (Closed) - 0
Medium (Open) - 1
Medium (Closed) - 0
Low (Open) - 3
Low (Closed) - 1
Please help me to solve this query, Thank You
You need to CROSS JOIN the distinct sets of severity and status values and then LEFT JOIN that to your table to allow you to count the values of each severity/status combination. Without sample data it's hard to be certain but something like this should work:
SELECT sv.vseverity, st.vulnstatus, COUNT(v.vseverity) AS count
FROM (
SELECT DISTINCT vseverity
FROM datasets
) sv
CROSS JOIN (
SELECT DISTINCT vulnstatus
FROM vulnsummary
) st
LEFT JOIN (
SELECT d.vseverity, v.vulnstatus
FROM vulnsummary v
JOIN project p ON v.projid = p.projid
AND v.stagename = p.currentstage
JOIN datasets d ON v.vtitleid = d.datasetid
) v ON v.vseverity = sv.vseverity AND v.vulnstatus = st.vulnstatus
GROUP BY sv.vseverity, st.vulnstatus
I don't have your full dataset, however, a RIGHT OUTER JOIN to a master volnstatus table will enable (the volnstatus table showing all options i.e. 'Open', 'Closed'). A rough draft example, with only the volnstatus table populated:
SELECT COUNT(s.vulnstatus) CountOf, t.vtype
FROM dbo.vusummary s
RIGHT OUTER JOIN
vusummarytype t
ON s.vulnstatus = t.vtype
GROUP BY t.vtype

An explanation with SQL query

I trying to get some data for my JavaFX Application from a couple of tables in database with MySQl.
Here's the query:
select veturattable.id, veturattable.vetura,veturattable.modeli,veturattable.ngjyra,
veturattable.targa, renttable.pagesa, hargjimettable.shuma
from veturattable
left join hargjimettable
on hargjimettable.veturaid= veturattable.id
left join renttable
on renttable.veturaid = veturattable.id ;
Here are datas from rentable
And here are datas from hargjimettable
So what I need is to show me this one:
veturaid | pagesa | shuma
1 | 150 | 91
10 | 110 | 40
You actually need to do two subqueries pre-aggregating the sum amounts per respective ID. Then join each individually back to the main. If you don't, you are getting a Cartesian product. For every record in the hargjimettable table for a given ID, it is joined to the renttable for each amount there. So, if you have 2 records in first table and 3 records in the second, you are getting a multiple of 6.
By pre-querying each grouping by the one ID key respectively, you will only have at most, one record for each possible summation. So grab that record if it exists. The left-join prevents some IDs from not showing up. Using coalesce() prevents nulls from showing.
select
v.id,
v.vetura,
v.modeli,
v.ngjyra,
v.targa,
COALESCE( RSum.SumPagesa, 0 ) as AllPagesa,
COALESCE( HSum.SumShuma, 0 ) as AllShuma
from
veturattable v
left join
( select
h.veturaid,
SUM( h.shuma ) as SumShuma
from
hargjimettable h
group by
h.veturaid ) HSum
ON v.id = HSum.veturaid
left join
( select
r.veturaid,
SUM( r.pagesa ) as SumPagesa
from
renttable r
group by
r.veturaid ) RSum
ON v.id = RSum.veturaid
You actually want the MAX() and SUM() along the GROUP BY like
select max(veturattable.id) as id, max(veturattable.vetura) as vetura,
max(veturattable.modeli) as modeli,
max(veturattable.ngjyra) as ngjyra,
max(veturattable.targa) as targa,
max(renttable.pagesa) as pagesa,
sum(hargjimettable.shuma) as shuma
from veturattable
left join hargjimettable
on hargjimettable.veturaid= veturattable.id
left join renttable
on renttable.veturaid = veturattable.id
group by veturattable.id;

SQL Select outter Join and Group By and IFNULL ( COUNT ) HELP =x

I have this database and i was wondering to create a great select but is too hard for me I guess I tried so many ways and I get really close, but i cant go longer.
Database
Table -> Candidato | IdCandidato(int) | idNome(varchar)
Table -> Voto | idVoto(int) | Candidato_idCandidato(int) | DiaVotacao(date)
i am creating a web voting system and need i greate select to complet my graphics to show the total voting for each day for each candidate.
Candidato = candidate | voto = vote | diaVotacao = voting day (english translation)
I need i response like this:
|VotingDay---------|-----Candidate1----------|-----Candidate2------|--Candidate3
|2014-05-14-------|---13(total votes)---------|------------4------------|-----------10|
|2014-05-15-------|---18(total votes)---------|------------0------------|------------8|
and so far i got this:
|VotingDay---------|-----TOTAL Votes----------|-----Name------|
|2014-05-14-------|---13(total votes)---------|-Candidate1
|2014-05-14-------|---18(total votes)---------|-Candidate2
|2014-05-15-------|---10(total votes)---------|-Candidate1
|2014-05-15-------|----8(total votes)---------|-Candidate2
I used the following code:
SELECT voto.DiaVotacao, IFNULL(COUNT(voto.Candidato_idCandidato),0) as Votos, candidato.Nome
FROM candidato LEFT OUTER JOIN voto ON voto.Candidato_idCandidato=candidato.idCandidato
GROUP BY voto.DiaVotacao, voto.Candidato_idCandidato
Note that i want the count of the votes for each candidate for everey day and if there is no votes apear the number 0 to indicate no votes
did u guys understand?
You need to generate the full list of candidates and days and then do the left outer join. You can get the list of days from the votos table.
Note that when you use count(<column>), it will return 0 if all the values are NULL. There is no need for ifull() or coalesce():
SELECT d.DiaVotacao, COUNT(v.Candidato_idCandidato) as Votos, c.Nome
FROM candidato c cross join
(SELECT DISTINCT v.DiaVotacao FROM voto v
) d LEFT OUTER JOIN
voto v
ON v.Candidato_idCandidato = c.idCandidato and
v.DiaVotacao = d.DiaVotacao
GROUP BY d.DiaVotacao, v.Candidato_idCandidato;

MySQL join & search

I have a problem with joining some tables, heres my structure:
tbl_imdb:
fldID fldTitle fldImdbID
1 Moviename 0000001
tbl_genres:
fldID fldGenre
1 Action
2 Drama
tbl_genres_rel:
fldID fldMovieID fldGenreID
1 1 1
2 1 2
What I’m trying to do is a query that will find all movies that is both an action movie and drama, is this possible to do without a subquery, if so, how?
What I'm trying right now is:
SELECT tbl_imdb.*
FROM tbl_imdb
LEFT JOIN tbl_imdb_genres_rel ON ( tbl_imdb.fldID = tbl_imdb_genres_rel.fldMovieID )
LEFT JOIN tbl_imdb_genres ON ( tbl_imdb_genres_rel.fldGenreID = tbl_imdb_genres.fldID )
WHERE tbl_imdb_genres.fldGenre = 'Drama'
AND tbl_imdb_genres.fldGenre = 'Action';
But this dosnt work, however it does work if I only keep one of the two WHERE's, but thats not what I want.
Two ways to do it:
1
SELECT tbl_imdb.*
FROM tbl_imdb
INNER JOIN tbl_genres_rel rel_action
ON tbl_imdb.fldID = rel_action.fldMovieID
INNER JOIN tbl_genres genre_action
ON rel_action.fldGenreId = genre_action.fldID
AND 'Action' = genre_action.fldGenre
INNER JOIN tbl_genres_rel rel_drama
ON tbl_imdb.fldID = rel_drama.fldMovieID
INNER JOIN tbl_genres genre_drama
ON rel_drama.fldGenreId = genre_drama.fldID
AND 'Drama' = genre_drama.fldGenre
This method is on the same path as your original solution. 2 differences:
The join should be inner, not left because you're trying to get movies that certainly have the corresponding genre entry
Since you want to find 2 different generes, you'll have to do the join with tbl_genres_rel and tbl_genres twice, once for each particular genre you're interested in.
2
SELECT tbl_imdb.*
FROM tbl_imdb
INNER JOIN tbl_genres_rel
ON tbl_imdb.fldID = tbl_genres_rel.fldMovieID
INNER JOIN tbl_genres
ON tbl_genres_rel.fldGenreId = tbl_genres.fldID
AND tbl_genres.fldGenre IN ('Action', 'Drama')
GROUP BY tbl_imdb.fldID
HAVING COUNT(*) = 2
Again, the basic join plan is the same. Difference here is that we join to the tbl_genres_rel and tbl_genres path just once. This on itself fetches all genres for one film, and then filters for the one's you're interested in. The ones that qualify will now have 2 rows for each distinct value of tbl_imdb.fldId. The GROUP BY aggregates on that, flattening that into one row. By asserting in the HAVING clause that we have exactly 2 rows, we ensure that we keep only those rows that have both the genres.
(Note that this assumes that there is a unique constraint on tbl_genres_rel over {fldMovieID, fldGenreID}. If such a constraint is not present, you should consider adding it.)
LEFT JOIN is not applicable in your case because records should exist on both tables. And you need to count the instances of the movie
SELECT *
FROM tbl_imdb a
INNER JOIN tbl_genres_rel b
on a.fldID = fldMovieID
INNER JOIN tbl_genres c
on c.fldGenreID = b.fldID
WHERE c.fldGenre IN ('Drama', 'Action')
GROUP BY a.Moviename
HAVING COUNT(*) > 1