Query to return zero rows with COUNT(*) - mysql

I have seen a number of similar questions posted to StackOverflow and I haven't been successful in my attempts to apply them.
I would like to take an existing working COUNT(*) query and update it such that it also returns the rows with zero as the count value. I think that I need to use a LEFT JOIN but I'm not sure how to get it to work.
My current working query:
SELECT `VIC_HELMET_BELT`.`id`, `VIC_HELMET_BELT`.`HELMET_BELT` AS 'desc', COUNT(*) AS 'count' FROM `VIC_ACCIDENT`, `VIC_NODE`, `VIC_PERSON`, `VIC_VEHICLE`, `VIC_HELMET_BELT`
WHERE `VIC_NODE`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
AND `VIC_PERSON`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
AND `VIC_VEHICLE`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
AND `VIC_PERSON`.`SEATING_POSITION_Id` = 1
AND `VIC_HELMET_BELT`.`id` = `VIC_PERSON`.`HELMET_BELT_WORN`
GROUP BY `VIC_HELMET_BELT`.`id`
This returns the table:
id desc count
------ ----------------------------- --------
1 Seatbelt worn 390115
2 Seatbelt not worn 10158
4 Child restraint not worn 1
5 Seatbelt/restraint not fitted 1573
6 Helmet worn 60521
7 Helmet not worn 3495
8 Not appropriate 3635
9 Not known 168617
I would like the table to be returned with id=3 with a count of 0:
id desc count
------ ----------------------------- --------
1 Seatbelt worn 390115
2 Seatbelt not worn 10158
3 Child restraint worn 0
4 Child restraint not worn 1
5 Seatbelt/restraint not fitted 1573
6 Helmet worn 60521
7 Helmet not worn 3495
8 Not appropriate 3635
9 Not known 168617
In case it's not clear from the query, VIC_HELMET_BELT is a lookup table that is equivalent to the id and desc columns of the table above. The VIC_PERSONS.HELMET_BELT_WORN contains the values I am counting that correspond to the VIC_HELMET_BELT.id values.
Any commentary on the quality of my original SQL is also appreciated. I feel like I never really had a strong understanding of how to make the most of SQL queries.
In case you're interested, this is crash data from Victoria, Australia. You may have noticed that I have filtered for the driver only. I really hope the "Child restraint not worn" entry is just a typo!
Thanks in advance for your help.

Here you go
SELECT `VIC_HELMET_BELT`.`id`, `VIC_HELMET_BELT`.`HELMET_BELT` AS 'desc',
COUNT(`VIC_VEHICLE`.`ACCIDENT_NO`) AS 'count'
FROM `VIC_HELMET_BELT`
LEFT JOIN `VIC_PERSON` ON `VIC_HELMET_BELT`.`id` = `VIC_PERSON`.`HELMET_BELT_WORN` AND `VIC_PERSON`.`SEATING_POSITION_Id` = 1
LEFT JOIN `VIC_ACCIDENT` ON `VIC_PERSON`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
LEFT JOIN `VIC_NODE` on VIC_NODE`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
LEFT JOIN `VIC_VEHICLE` on `VIC_VEHICLE`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
GROUP BY `VIC_HELMET_BELT`.`id, `VIC_HELMET_BELT`.`HELMET_BELT`

Try this query below and see if there's any count result for ID=3. If it's null, you can use IFNULL(COUNT(*),0) AS 'Count':
SELECT `VIC_HELMET_BELT`.`id`, `VIC_HELMET_BELT`.`HELMET_BELT` AS 'desc',
COUNT(*) AS 'count'
FROM `VIC_HELMET_BELT`
LEFT JOIN `VIC_PERSON` ON `VIC_HELMET_BELT`.`id` = `VIC_PERSON`.`HELMET_BELT_WORN`
LEFT JOIN `VIC_ACCIDENT` ON `VIC_PERSON`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
LEFT JOIN `VIC_NODE` ON `VIC_NODE`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
LEFT JOIN `VIC_VEHICLE` ON `VIC_VEHICLE`.`ACCIDENT_NO` = `VIC_ACCIDENT`.`ACCIDENT_NO`
WHERE `VIC_PERSON`.`SEATING_POSITION_Id` = 1
GROUP BY `VIC_HELMET_BELT`.`id`
As for the comment on your query, you can try using aliases on your table for shorter query .. example below:
SELECT v1.`id`, v1.`HELMET_BELT` AS 'desc', COUNT(*) AS 'count'
FROM `VIC_HELMET_BELT` as v1
LEFT JOIN `VIC_PERSON` as v2 ON v1.`id` = v2.`HELMET_BELT_WORN`
LEFT JOIN `VIC_ACCIDENT` as v3 ON v2.`ACCIDENT_NO` = v3.`ACCIDENT_NO`
LEFT JOIN `VIC_NODE` as v4 ON v2.`ACCIDENT_NO` = v4.`ACCIDENT_NO`
LEFT JOIN `VIC_VEHICLE` as v5 ON v2.`ACCIDENT_NO` = v4`.`ACCIDENT_NO`
WHERE v2.`SEATING_POSITION_Id` = 1
GROUP BY v1.`id`;
Each of your table being assigned with v1, v2, v3 ... and so on so that when you want to use a column from the table, you don't need to type the full table name instead you just need to type the alias.
**Edit:**Another way you can do is like this, assuming that you need to perform other operation on other tables except for VIC_HELMET_BELT; which just solely become a reference table.
SELECT v1.`id`, v1.`HELMET_BELT` AS 'desc', COUNT(*) AS 'count'
FROM `VIC_HELMET_BELT` AS v1
LEFT JOIN
(SELECT * FROM `VIC_PERSON` AS v2
INNER JOIN `VIC_ACCIDENT` AS v3 ON v2.`ACCIDENT_NO` = v3.`ACCIDENT_NO`
INNER JOIN `VIC_NODE` AS v4 ON v2.`ACCIDENT_NO` = v4.`ACCIDENT_NO`
INNER JOIN `VIC_VEHICLE` AS v5 ON v2.`ACCIDENT_NO` = v4.`ACCIDENT_NO`
WHERE v2.`SEATING_POSITION_Id` = 1) A
ON v1.`id`=A.`HELMET_BELT_WORN`
GROUP BY v1.`id`;

Related

Contiditional WHERE with two joins on same table

I'm trying to create an effective query but can't get it working.
Tables:
- one table containing types of objects
- one table containing objects
Conditions:
- there can be single objects of a type
- there can be child objects of a type
- parent and child objects don't need to be of the same type
- objects can be published
- types can be published
- the results should only get pulled from a specific pool of object IDs. So i need to add AND (o.id IN (1,2,3,4)
I want a simple result list that shows how many types are published and the number of objects assigned to these types.
types
id | title | published
---------------------
1 type1 1
2 type2 1
3 type3 1
4 type4 1
5 type5 1
6 type6 0
7 type7 1
objects
id |title | type | parent | published
---------------------------------------
1 a 1 0 1
2 b 1 0 1
3 c 3 2 1
4 d 2 0 1
5 e 2 2 1
6 f 4 0 0
7 g 5 6 1
8 h 6 0 1
9 i 3 8 1
10 j 3 8 0
11 k 7 8 1
Results should be:
type1 (#2) (two singles)
type2 (#2) (one single + one child of id 2)
type3 (#3) (one child of id 2 + one published child of id 8)
type4 (#0) (one single not published)
type5 (#0) (because it's parent id 6 is not published)
type6 (#0) (because type6 is not published)
I tried this one (type publishing not included):
SELECT o.type, t.title, COUNT(t.id) AS cnt
FROM types AS t
LEFT JOIN objects AS o ON o.type = t.id
LEFT JOIN objects AS o2 ON o.id = o2.parent
WHERE o.published = 1 AND o2.published = 1
GROUP BY o.type
The conditions in the WHERE clause negate the "outerness" of the left joins.
Move those conditions to the ON clauses. The WHERE clause can be dropped.
Also, reference columns from t, the driving table, and count non-NULL expressions from the outer joined tables.
That will allow the query to return zero counts.
I didn't fully delve into the specification, but it looks like we want to count matching rows from o and o2.
I think something like this will get a resultset consistent with one interpretation of the specification... child o2 rows get counted under parent o type, regardless of the type on the child o2 row.
This is not tested, and I'm not fully understanding the specification...
SELECT t.id AS `type`
, t.title AS `title`
, COUNT(DISTINCT o.id)
+ COUNT(DISTINCT o2.id) AS `cnt`
-- , COUNT(DISTINCT o.id) AS `cnt_o`
-- , COUNT(DISTINCT o2.id) AS `cnt_o2`
FROM types t
LEFT
JOIN objects o
ON o.type = t.id
AND o.published = 1
AND o.parent = 0
AND t.published = 1
LEFT
JOIN objects o2
ON o2.parent = o.id
AND o2.published = 1
GROUP
BY t.id
, t.title
Not clear in the spec...
Do child rows (from o2) get omitted from the count if the type on the o2 row matches a row in types that is published=0 ?
If we are "grouping" by type on the o2 rows , then we'd need to something different,
EDIT
we could get the count from the parent and the child separately, in two separate SELECT, and then combine the two resultsets with a UNION ALL set operator, and then total up the counts.
something along these lines:
SELECT c.type
, c.title
, SUM(c.cnt) AS cnt
FROM (
SELECT t.id AS `type`
, t.title AS `title`
, COUNT(o.id) AS `cnt`
FROM types t
LEFT
JOIN objects o
ON o.type = t.id
AND o.published = 1
AND o.parent = 0
AND t.published = 1
GROUP
BY t.id
, t.title
UNION ALL
SELECT tc.id AS `type`
, tc.title AS `title`
, COUNT(oc.id) AS `cnt`
FROM types tc
JOIN objects oc
ON oc.type = t.id
AND oc.published = 1
AND t.published = 1
JOIN objects op
ON op.id = oc.parent
AND op.published = 1
JOIN types pt
ON pt.id = op.type
AND pt.published = 1
GROUP
BY tc.id
, tc.title
) c
GROUP
BY c.type
, c.title
again, untested, and without a full understanding of the spec.
the count of the parent o is straightforward. we use an outer join, with t as the driving table, so we get all types, and can get zero counts.
the count of the child oc, we can do inner joins. since the previous SELECT is getting us all the types, missing rows in the second SELECT won't cause a problem.
note that we join the child o2 rows by type, and then we join to parent (to make sure parent is published), and join to parent type (to check that type is published) ...
How do we distinguish "parent" rows, do we check parent=0 ?
Is this a hierarchy, can a "child" also be the "parent" of another row ?
FOLLOWUP
Another way to think about it (maybe this was the approach of the OP query) ... we are counting rows from o, parents and children. What's important is that the type is published type, and that o is published.
Additionally, either
o is not a child (i.e. there isn't a row in objects op that has an id value equal to `o.parent)
or
if o does have a parent row (a row in objects op with an id value equal to o.parent, the [parent op is published and the parent type is published.
We could approach it like this:
SELECT t.id AS `type`
, t.title AS `title`
, COUNT(o.id) AS `cnt`
FROM types t
LEFT
JOIN objects o
ON o.type = t.id
AND o.published = 1
AND t.published = 1
LEFT
JOIN objects op
ON op.id = o.parent
LEFT
JOIN types pt
ON pt.id = op.type
WHERE -- this not a child (there is no parent)
op.id IS NULL
OR -- parent is published and parent type is published
( op.published = 1 AND pt.published = 1 )
GROUP
BY t.id
, t.title

MySQL query with INNER JOIN and LEFT JOIN

So i have a database with some tables. Now i want a query that gets data from 3 tables. First lets see what the databases are
omschrijvingVoorraad
-ID 1
-userID 1
-omschrijvingID 6
-min 4
omschrijving
-ID 6
-omschrijving Cola (blikje 330ml)
voorraad
-ID 20
-userID 1
-omschrijvingID 6
-aantal 2
Now i want to make a query that will show the next line:
Cola (blikje 330ml) Aantal 2 minmaal 4
I searched around and came up with below but it is not working. It doesn't give an error but just an empty result
$queryOm="SELECT omschrijvingVoorraad.ID, omschrijvingID, omschrijving, vAantal, min
FROM omschrijvingVoorraad
LEFT JOIN omschrijving ON omschrijving.ID = omschrijvingVoorraad.omschrijvingID
INNER JOIN ( SELECT omschrijvingID vid, SUM( aantal ) vAantal
FROM voorraad WHERE userID='$userID' ) p ON vid = omschrijvingVoorraad.omschrijvingID
WHERE userID='$userID'
LIMIT $offset, $perPage";
Where offcourse the $offset and $perPage are being defined earlier in the code.
So can anyone tell me where I went wrong? What should I change to get the correct result?
Looking to your schema and your expected result seem you need this query
select a.ID, a.omschrijvingID, b.omschrijving, sum(c.aantal), a.min
from omschrijvingVoorraad as a
inner join omschrijving as b on a.omschrijvingID = b.ID
inner join voorraad as c on a.omschrijvingID = c.omschrijvingID
group by a.ID, a.omschrijvingID, b.omschrijving, a.min

combine tables with 1 to N relationship into 1 line of record with the last value of the N record

I need a modification of my previous post regarding
how to combine tables with 1 to many relationship into 1 line of record
how to combine tables with 1 to many relationship into 1 line of record
now my problem is my record has now 1 to many relationship. What I need to show is the last record only and combine it in a single line
tables tbl_equipment and tbl_warranty
and here is the desired output
here is the code I'm trying to implement
SELECT
a.equipmentid,
a.codename,
a.name,
a.labelid,
a.ACQUISITIONDATE,
a.description,
a.partofid,
w1.warrantyid as serviceidwarranty,
w1.startdate,
w1.enddate,
w2.warrantyid as productidwarranty,
w2.startdate,
w2.enddate,
s.equipstatusid,
l.equiplocationid FROM TBL_EQUIPMENTMST a
left JOIN tbl_equipwarranty w1
ON w1.equipmentid=a.equipmentid and w1.serviceproduct = 'service'
left JOIN tbl_equipwarranty w2
ON w2.equipmentid=a.equipmentid and w2.serviceproduct = 'product'
left join tbl_equipstatus s
on a.equipmentid = s.equipmentid
left join tbl_equiplocation l
on a.equipmentid = l.equipmentid WHERE a.equipmentid = '112'
I only want to show 1 record with the last value of warranty product and warranty service in the output. Can anyone guide me how to modify my code so that when I try join all the tables listed above can produce 1 record only with the last record of warranty as an output.
I am using firebird as a database. If you have a solution in mysql kindly tell me and ill try to find the counterpart in firebird.
with summary as(
select e.equipmentid ,e.Codename,e.Name,w.warrantyid ,w.Satartdate ,w.Enddate,w.warrantytype
from Eqp e
join Warranty w
on(w.equipmentid =e.equipmentid )
where w.warrantyid =3)
select *,w.warrantyid,w.Satartdate ,w.Enddate,w.warrantytype
from summary s
join Warranty w
on s.Satartdate =w.Satartdate and s.Enddate =w.Enddate
where w.warrantyid =4
after reading the comment of Barmar at the question for solution. I Figured out subquery can solve my problem. Subquery is a new word for me. I research on how to use subquery and came out with a solution below. you can correct me if my code is wrong or how to improve the performance of the query
SELECT
a.equipmentid,a.codename,a.name,a.labelid,a.ACQUISITIONDATE,a.description,a.partofid,
w1.warrantyid as serviceidwarranty,w1.startdate,w1.enddate,
w2.warrantyid as productidwarranty,w2.startdate,w2.enddate,
s.equipstatusid,
l.equiplocationid
FROM
TBL_EQUIPMENTMST a
left JOIN
(select first 1 *
from tbl_equipwarranty
where equipmentid='112' and serviceproduct = 'service'
order by warrantyid desc) w1 ON w1.equipmentid = a.equipmentid
and w1.serviceproduct = 'service'
left JOIN
(select first 1 *
from tbl_equipwarranty
where equipmentid = '112' and serviceproduct = 'product'
order by warrantyid desc) w2 ON w2.equipmentid = a.equipmentid
and w2.serviceproduct = 'product'
left join
(select first 1 *
from tbl_equipstatus
where equipmentid = '112'
order by equipstatusid desc) s on a.equipmentid = s.equipmentid
left join
(select first 1 *
from tbl_equiplocation
where equipmentid = '112'
order by equiplocationid desc) l on a.equipmentid = l.equipmentid
WHERE
a.equipmentid = '112'

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

How to left join or inner join a table itself

I have this data in a table, for instance,
id name parent parent_id
1 add self 100
2 manage null 100
3 add 10 200
4 manage null 200
5 add 20 300
6 manage null 300
How can I left join or inner join this table itself so I get this result below?
id name parent
2 manage self
4 manage 10
6 manage 20
As you can I that I just want to query the row with the keyword of 'manage' but I want the column parent's data in add's row as the as in manage's row in the result.
Is it possible?
EDIT:
the simplified version of my actual table - system,
system_id parent_id type function_name name main_parent make_accessible sort
31 30 left main Main NULL 0 1
32 31 left page_main_add Add self 0 1
33 31 left page_main_manage Manage NULL 0 2
my actual query and it is quite messy already...
SELECT
a.system_id,
a.main_parent,
b.name,
b.make_accessible,
b.sort
FROM system AS a
INNER JOIN -- self --
(
SELECT system_id, name, make_accessible, sort
FROM system AS s2
LEFT JOIN -- search --
(
SELECT system_id AS parent_id
FROM system AS s1
WHERE s1.function_name = 'page'
) AS s1
ON s1.parent_id = s2.parent_id
WHERE s2.parent_id = s1.parent_id
AND s2.system_id != s1.parent_id
ORDER BY s2.sort ASC
) b
ON b.system_id = a.parent_id
WHERE a.function_name LIKE '%manage%'
ORDER BY b.sort ASC
result I get currently,
system_id main_parent name make_accessible sort
33 NULL Main 0 1
but I am after this,
system_id main_parent name make_accessible sort
33 self Main 0 1
You just need to reference the table twice:
select t1.id, t1.name, t2.id, t2.name
from TableA t1
inner join TableA t2
on t1.parent_id = t2.Id
Replace inner with left join if you want to see roots in the list.
UPDATE:
I misread your question. It seems to me that you always have two rows, manage one and add one. To get to "Add" from manage:
select system.*, (select parent
from system s2
where s2.parent_id = system.parent_id
and s2.name = 'add')
AS parent
from system
where name = 'manage'
Or, you might split the table into two derived tables and join them by parent_id:
select *
from system
inner join
(
select * from system where name = 'add'
) s2
on system.parent_id = s2.parent_id
where system.name = 'manage'
This will allow you to use all the columns from s2.
Your data does not abide to a child-parent hierarchical structure. For example, your column parent holds the value 10, which is not the value of any id, so a child-parent association is not possible.
In other words, there's nothing that relates the record 2,manage,null to the record 1,add,self, or the record 4,manage,null to 3,add,10, as you intend to do in your query.
To represent hierarchical data, you usually need a table that has a foreign key referencing it's own primary key. So your column parent must reference the column id, then you can express a child-parent relationship between manage and add. Currently, that's not possible.
UPDATED: Joining by parent_id, try:
select m.id, m.name, a.parent
from myTable m
join myTable a on m.parent_id = a.parent_id and a.name = 'add'
where m.name = 'manage'
Change the inner join to a left join if there may not be a corresponding add row.