SQL query regarding nested query topic - mysql

Query that displays all "Father (Husband)" names in alphabetical order from Guardian table with total number of their "Wives" (use nested query to find count of wives).
enter image description here

You could use a self join and group by
select a.guardianName as husband_name, count(*) as count_of_wives
from my_table a
left join my_table b on b.husband_id = a.guardianId
where a.husband_id is null
group by a.guardianName

Related

Join mysql table with distinct value from another table

I encountered a problem on a database I am working with. I have a table of counsels which may hold repeating values, but their is an enrolment number filed which is unique and can be used to fetch them. However, I want to join from a cases_counsel table on the "first" unique value of the counsel table that matches that column on the cases counsel table.
I want to list the cases belonging to a particular counsel using the enrolment_number as the counsel_id on the cp_cases_counsel table. That means I want to pick just a distinct value of a counsel, then use it to join the cp_cases_counsel table and also return the count for such.
However, I keep getting duplicates. This was the mysql query I tried
SELECT T.suitno, T.counsel_id, COUNT(*) as total from cp_cases_counsel T
INNER JOIN (SELECT
enrolment_number as id, MIN(counsel)
FROM
cp_counsel
GROUP BY
enrolment_number
) A
ON A.id = T.counsel_id
GROUP BY T.suitno, T.counsel_id
and
SELECT enrolment_number as id, MIN(counsel) as counsel, COUNT(*) as total FROM cp_counsel
JOIN cp_cases_counsel ON cp_cases_counsel.counsel_id = cp_counsel.enrolment_number
GROUP BY enrolment_number
For the second query, it's joining twice and I am having like double of what I am supposed to get.
The columns that you want in the results are councel (actually only one of all its values) from cp_counsel and counsel_id from cp_cases_counsel, so you must group by them and select them:
SELECT a.counsel, t.counsel_id, COUNT(*) AS total
FROM cp_cases_counsel t
INNER JOIN (
SELECT enrolment_number, MIN(counsel) AS counsel
FROM cp_counsel
GROUP BY enrolment_number
) a ON a.enrolment_number = t.counsel_id
GROUP BY a.counsel, t.counsel_id;

Get a row which has the maximum id

Problem in simple words, 1st must be left joined to the 2nd table where the record is latest. So, I use an approach of using function MAX()
Currently I have 2 tables.
matches
matches_payments
|
Now I want to join the second table to first one using MAX(id) on matches_payments
Desired result
but I am not getting desired result due to greatest-n-per-group problem.
Query
SELECT matches.id, mp.*
FROM matches
LEFT JOIN (SELECT
MAX(id) AS id,
match_id
paymentStatus
FROM matches_payments
GROUP BY match_id) AS mp ON mp.id = matches.id;
Desired result is not produced due to : Stackoverflow Question
When using this feature, all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.
FROM MySQL Dev
PS : I know the tables are poorly designed. It is not my work as the last developer did those.
You need two joins. You need a self-join of the matches_payments table to get the row with the highest ID for each match_id, as shown in SQL Select only rows with Max Value on a Column. Then you LEFT JOIN this to matches to combine the two tables:
SELECT m.*, mp.paymentStatus, mp.paymentAmount
FROM matches AS m
LEFT JOIN (
SELECT mp1.*
FROM matches_payments AS mp1
JOIN (SELECT match_id, MAX(id) AS id
FROM matches_payments
GROUP BY match_id) AS mp2
ON mp1.match_id = mp2.match_id AND mp1.id = mp2.id
) AS mp ON mp.match_id = m.id

MySQL Two Table Query Count

I have two tables A & B.
Table A
GROUP # | GROUP NAME
1 group a
2 group b
3 group c
Table B will have a column with group # and then a bunch of other data.
I'm trying to figure out how I can create a query that will return the GROUP NAME from TABLE A and the number of rows associated with each group name from TABLE B.
Essentially I'm trying to get the following output:
GROUP NAME | COUNT
group a x
group b y
group c z
I've been trying variations of the following to no avail...
SELECT DISTINCT "GROUP NAME", COUNT(*) from A, B where A.GROUPNUM = B.GROUPNUM;
You will need to apply the aggregate COUNT() over the group GROUP NAME (using GROUP BY) to get the count you are looking for. DISTINCT doesn't come into play in this instance,
Note that a column name with spaces will need to be quoted using backticks, not single or double quotes. I'm also replacing your implicit join with an explicit INNER JOIN, which is the modern preferred syntax.
SELECT
`GROUP NAME`,
COUNT(B.GROUPNUM)
FROM
A
INNER JOIN B ON A.GROUPNUM = B.GROUPNUM
GROUP BY `GROUP NAME`
Here's a little demonstration: http://sqlfiddle.com/#!2/2123f/2
Try the below, note that you will want to use a left join (like below) if you also want to show group names on table a that have no rows on table b.
select a.group_name, count(b.groupnum)
from a
left join b
on a.groupnum = b.groupnum
group by a.group_name

MySQL join on max value

From joining the tables below on the entry.id, I want to extract the rows from the food_brands table which have the highest type_id - so I should be getting the top 3 rows below, with type_id 11940
food_brands
id brand type_id
15375 cesar 11940
15374 brunos 11940
15373 butchers 11940
15372 bakers 11939
15371 asda 11939
15370 aldi 11939
types
id type quantity food_id
11940 comm 53453 10497
11939 comm 999 10496
foods
id frequency entry_id
10497 twice 12230
10496 twice 12230
10495 once 12230
entries
id number
12230 26
My attempt at the query isn't filtering out the lower type.id records - so from the table records below in food_brands, i'm getting those with type_id 11940 and 11939. Grateful for any help fix this!
SELECT fb.*
FROM food_brands fb
INNER JOIN types t ON fb.type_id = t.id
INNER JOIN
(
SELECT MAX(id) AS MaxID
FROM types
GROUP BY id
) t2 ON t.food_id = t2.food_id AND t.id = t2.MaxID
INNER JOIN foods f ON t.food_id = f.id
INNER JOIN entries e ON f.entry_id = e.id
WHERE entries.id = 12230
A simple subquery should do it just fine;
SELECT * FROM food_brands WHERE type_id=
(SELECT MAX(t.id) tid FROM types t
JOIN foods f ON f.id=t.food_id AND f.entry_id=12230)
An SQLfiddle to test with.
If you just want to return the rows from food_brands with the max type id, you should be able to use:
SELECT fb.*
FROM food_brands fb
INNER JOIN
(
select max(id) id
from types
) t
on fb.type_id = t.id
See SQL Fiddle with Demo
I don't know why you are doing all these inner joins after the one on the t2 subquery, since you are only retrieving the columns of fb, but I suppose that you are not showing the whole query, and you just want to get that one fixed.
The issue is actually in the subquery t2: there, for some untold reason, you choose to do a GROUP BY id which changes the MAX function semantic to generate a maximum value per id, and since you are asking the maximum on that very column, MAX and GROUP BY cancel out each other. Just removing the GROUP BY clause fixes the query.
If for some untold reason you cannot remove that clause, perhaps replacing MAX(id) by id and adding ORDER BY id DESC LIMIT 1 would do.
Also, your subquery should probably select also food_id since it is used in the subsequent INNER JOIN clause.

The following SQL zoo query is apparently wrong

I have a problem with the following exercise query on this page http://sqlzoo.net/3.htm :
4d. List the 1978 films by order of cast list size.
I'm trying to do the query:
SELECT DISTINCT(m1.title), COUNT(c1.actorid)
FROM ((movie AS m1 JOIN casting AS c1 ON m1.id=c1.movieid) JOIN actor AS a1 ON a1.id=c1.actorid)
WHERE m1.yr=1978
GROUP BY m1.title
ORDER BY COUNT(c1.actorid) DESC
But it doesn't give the right answer, and I don't know why. Am I wrong?
This should do it:
select m.title, count(c.actorid)
from movie m
join casting c on c.movieid = m.id
where m.yr = 1978
group by m.title
order by 2 desc
As you don't need any information from the actors, you don't need to include that table in the join.
Btw: your usage of distinct shows two misunderstandings:
distinct is not a function. It always operates on all columns of the result
when you do a group by there is no need to also to a distinct (as the group by will already return only the distinct values of the grouped columns)