MYSQL - Join only the lastest row from the second table - php

I have patients table and appointments table. I want to query appointments from today and join patient info on the query.
This
SELECT a.PatientID, a.DoctorID, a.DT,
p.id, p.Name
FROM appointment a
JOIN Patient p
ON p.id = a.PatientID
WHERE DATE(DT) = CURDATE()
GROUP BY p.id
ORDER BY a.DT DESC
Works, but it shows the first row it finds (usually the older one) not respecting the order by (to show only the latest by patient). What am I missing here?
UPDATE:
Sorry, I should write it more properly.
Patient table:
id Name
1 Jonathan
2 Helena
Appointment table
PatientID DoctorID DT
1 1 2021-08-27 09:30
2 1 2021-08-27 10:00
1 1 2021-08-27 11:00
If I query as I have it, the return will be
1 1 2021-08-27 09:30
2 1 2021-08-27 10:00
Instead of
2 1 2021-08-27 10:00
1 1 2021-08-27 11:00

Use window function for retrieving the patient wise latest date record. Then join patient table. If all patient info is needed then use LEFT JOIN instead of INNER JOIN.
-- MySQL (v5.8)
SELECT p.id PatientID
, p.Name patient_name
, t.DoctorID
, t.DT
FROM Patient p
INNER JOIN (SELECT PatientID
, DoctorID
, DT
, ROW_NUMBER() OVER (PARTITION BY PatientID ORDER BY DT DESC) row_num
FROM Appointment) t
ON p.id = t.PatientID
AND t.row_num = 1
ORDER BY t.DT;
Please check from url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=944f2dd72105bc9fb06b1a6b5fd837f2
For lower version where window functions are not supported.
-- MySQL(v5.6)
SELECT p.id PatientID
, p.Name patient_name
, tmp.DoctorID
, tmp.DT
FROM Patient p
INNER JOIN (SELECT #row_no := IF(#prev_val = t.PatientID, #row_no + 1, 1) AS row_number
, #prev_val := t.PatientID PatientID, t.DoctorID, t.DT
FROM Appointment t,
(SELECT #row_no := 0) x,
(SELECT #prev_val := 0) y
ORDER BY t.PatientID, t.DT DESC) tmp
ON p.id = tmp.PatientID
AND tmp.row_number = 1
ORDER BY tmp.DT;
Please check from url https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=d665ffe9f3d09df23513ad50be31b388

Related

mysql left outer join ranking

I'm trying to rank with the left outer join
My sql is :
SET #rank=0;
SELECT #rank:=#rank+1 AS rank, h.name, COUNT(v.hId) AS votes
FROM users h LEFT OUTER JOIN users_votes v ON h.id = v.hId GROUP BY h.id
ORDER BY rank ASC
;
The right thing would be to return like this
rank | name | votes
1 Luck 4
2 Marc 3
3 Santos 2
4 Matheus 0
But it's returning the wrong way:
rank | name | votes
1 Santos 2
2 Marc 3
3 Luck 4
4 Matheus 0
You are ordering in ASC way, change it to DESC. Like this:
SET #rank=0;
SELECT #rank:=#rank+1 AS rank, h.name, COUNT(v.hId) AS votes
FROM users h LEFT OUTER JOIN users_votes v ON h.id = v.hId GROUP BY h.id
ORDER BY rank DESC
;
In MySQL 8+, you should use row_number():
SELECT ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as rank,
h.name, COUNT(*) AS votes
FROM users h LEFT OUTER JOIN
users_votes v
ON h.id = v.hId
GROUP BY h.id
ORDER BY rank ASC;
Variables are deprecated in 8+.
In earlier version, you can use variables, but they tend not to respect ORDER BY or GROUP BY. So, with those constructs, you need a subquery:
SELECT (#rn := #rn + 1) as rank, hv.*
FROM (SELECT h.name, COUNT(*) AS votes
FROM users h LEFT OUTER JOIN
users_votes v
ON h.id = v.hId
GROUP BY h.id
ORDER BY rank ASC
) hv CROSS JOIN
(SELECT #rn := 0) params;
Doesn't works, the rank number is wrong. I want to sort by votes and rank the most voted

Select distinct info from each user where time is MAX

A have a reservation that looks something like this:
id payable time name floor
1 24 02:40:10 Benjamin 15th
2 36 02:29:10 Beverlyn 15th
3 48 02:35:16 Benjamin 15th
4 30 02:32:51 Beverlyn 15th
And an orders table where the orders details of a customer is stored.
id product
1 A
2 B
3 C
4 D
I want to return ONLY latest record from each user that is inserted. Something like this:
payable time name floor product
24 02:40:10 Benjamin 15th A
30 02:32:51 Beverlyn 15th D
attempted query:
SELECT reservation.payable, reservation.time, reservation.name, reservation.floor, orders.product
FROM orders
INNER JOIN reservation
ON orders.id = reservation.id
WHERE reservation.time =
(SELECT MAX(time)
FROM reservation)
&& reservation.floor='15th';
problem is it only returns a SINGLE record who last inputted a even names are of the users different. Which is in the case only returns this:
payable time name floor product
24 02:40:10 Benjamin 15th A
use corelated subquery
SELECT r.*,o.product
FROM reservation r
join order o ON o.id = r.id
where r.time =( select max(time) from reservation r1 where r1.name=r.name)
Using joins -
SELECT t1.payable,
t1.time,
t1.NAME,
t1.floow,
t3.product
FROM reservation t1
INNER JOIN
(
SELECT Max(time) max_time,
NAME
FROM reservation
GROUP BY NAME) t2 t1.NAME=t2.NAME
AND t1.time=t2.max_time
INNER JOIN product t3
ON (
t1.id=t3.id)
SELECT r.payable, r.time, r.name, r.floor, o.product
FROM orders as o
INNER JOIN reservation as r
ON o.id = r.id
WHERE r.time =
(SELECT MAX(time)
FROM reservation where name=r.name)
&& r.floor='15th';
You can try something like this:
/* Create tables */
CREATE TEMP TABLE orders AS
(
SELECT 1 AS id, 'A' AS product UNION
SELECT 2, 'B' UNION
SELECT 3, 'C' UNION
SELECT 4, 'D'
);
CREATE TEMP TABLE reservations AS
(
SELECT 1 AS id, 24 AS payable, '02:40:10'::TIME AS time, 'Benjamin' AS name, '15th' AS floor UNION
SELECT 2, 36 , '02:29:10 '::TIME, 'Beverlyn', '15th'UNION
SELECT 3, 48 , '02:35:16'::TIME, 'Benjamin', '15th'UNION
SELECT 4, 30 , '02:32:51 '::TIME, 'Beverlyn', '15th'
);
/* Final Selection */
SELECT a.id
, a.payable
, a.time
, a.name
, a.floor
, b.product
FROM reservations a
LEFT JOIN orders b on a.id = b.id
WHERE (name, time) IN (SELECT name, MAX(time) AS time
FROM reservations
GROUP BY 1)
ORDER BY 1;
Alternately you can also use window functions.

multiple count and sum MySQL function returning wrong values with multiple joins in MySQL result

Table mpkids_students AS A
id BranchId Email Mobile StudentId
9497 25 mpsuraj2016#gmail.com 8700698773 25
9498 25 m016#gmail.com 8700698776 26
Table mpkids_student_image_gallery AS B
id like_count student_id
1 25 27
Table mpkids_visitors AS C
id student_id
1 9497
2 9497
3 9497
Table mpkids_visitors_count AS D
id visitor_count student_id
1 4 23
Table mpkids_image_likes AS E
id student_id
1 67
Table mpkids_relatives_data AS F
id student_id rel_email rel_mobile
1 9497 kushwahji#gmail.com 9009859691
2 9497 kushwah#gmail.com 7566403326
3 9497 kushwah#gmail.com 1236403326
4 9497 suraj#gmail.com 123640332
Table mpkids_paidstatus AS G
id student_id Received
1 9497 7500
2 9497 3000
3 9497 3000
MYSQL QUERY
SELECT A.id as student_id,
COUNT(DISTINCT B.id) as images,
COUNT(DISTINCT C.id)+ COUNT(DISTINCT D.visitor_count) as visits,
count(DISTINCT E.id) + SUM(B.like_count) as likes,
COUNT(DISTINCT A.Email)+COUNT(DISTINCT F.rel_email) as emails,
COUNT(DISTINCT A.Mobile)+COUNT(DISTINCT F.rel_mobile) as moibles,
SUM(G.Received) as Received
FROM mpkids_students AS A
LEFT JOIN mpkids_student_image_gallery AS B ON B.student_id = A.id
LEFT JOIN mpkids_visitors AS C ON C.student_id = A.id
LEFT JOIN mpkids_visitors_count AS D ON D.student_id = A.id
LEFT JOIN mpkids_image_likes AS E ON E.student_id = A.id
LEFT JOIN mpkids_relatives_data AS F ON F.student_id = A.id
LEFT JOIN mpkids_paidstatus AS G ON G.student_id = A.id
WHERE A.BranchId = 25
GROUP BY A.id
ORDER BY A.StudentId DESC
Result:
student_id images visits likes emails moibles Received
9497 0 3 NULL 4 5 202500
9498 0 0 NULL 1 1 NULL
Problem Explanation:
Received Field returning wrong value i have tried many queries but not getting solution
Received Field correct value 13500 for student_id = 9497
Please help me to find solution.
You are getting wrong output because, when you are joining based on studentid, you are getting multiple records from mpkids_paidstatus table for each student, which is adding up and returning a wrong output.
You can also write your query like following using subquery.
SELECT A.id as student_id,
COUNT(DISTINCT B.id) as images,
COUNT(DISTINCT C.id)+ COUNT(DISTINCT D.visitor_count) as visits,
count(DISTINCT E.id) + SUM(B.like_count) as likes,
COUNT(DISTINCT A.Email)+COUNT(DISTINCT F.rel_email) as emails,
COUNT(DISTINCT A.Mobile)+COUNT(DISTINCT F.rel_mobile) as moibles,
(select SUM(Received) from mpkids_paidstatus ps where ps.student_id=a.id) as Received
FROM mpkids_students AS A
LEFT JOIN mpkids_student_image_gallery AS B ON B.student_id = A.id
LEFT JOIN mpkids_visitors AS C ON C.student_id = A.id
LEFT JOIN mpkids_visitors_count AS D ON D.student_id = A.id
LEFT JOIN mpkids_image_likes AS E ON E.student_id = A.id
LEFT JOIN mpkids_relatives_data AS F ON F.student_id = A.id
WHERE A.BranchId = 25
GROUP BY A.id
ORDER BY A.StudentId DESC

Select results from table1 based on entries on table2

I have 2 tables;
banner_views (id, b_id, b_date)- this record a banner view every time it gets displayed
banners_dynamic (id, status, static_iname, static_keywords, static_url, static_alt, static_type, static_image, b_views, b_clicks) - stores the banner data
I would like to select 3 banners_dynamic results which have had the least views in the last 7 days.
I did put somethign together (see below) but I realised it was grabbing the total views for all banner rather than uniquely by id.
SELECT *,
(SELECT COUNT(*) FROM banner_views v WHERE v.b_date >= DATE(NOW()) - INTERVAL 7 DAY) as post_count
FROM banners_dynamic b
WHERE static_keywords LIKE '%test%' AND b.status='1' AND b.static_type='1'
ORDER BY post_count ASC LIMIT 3
Can anyone point me in the correct direction?
You must join both banners_dynamic table and your subquery with corresponding banner IDs:
SELECT
b.*, p.b_count
FROM
banners_dynamic b
INNER JOIN (
SELECT
b_id,
COUNT(*) AS b_count
FROM
banner_views v
WHERE
v.b_date >= DATE(NOW() - INTERVAL 7 DAY)
GROUP BY
b_id
) p on p.b_id = b.id
WHERE
b.static_keywords LIKE '%test%'
AND b.`status` = '1'
AND b.static_type = '1'
ORDER BY
p.b_count ASC
LIMIT 3
UPDATE: You can do it even without subquery:
SELECT
b.*, COUNT(v.b_id) AS b_count
FROM
banners_dynamic b
INNER JOIN banner_views v ON v.b_id = b.id
WHERE
v.b_date >= DATE_ADD(NOW(), INTERVAL - 7 DAY)
AND b.static_keywords LIKE '%test%'
AND b.`status` = '1'
AND b.static_type = '1'
GROUP BY
v.b_id
ORDER BY
b_count ASC
LIMIT 3;
If you want to include banners without any views (count=0) then you must do a LEFT JOIN:
SELECT
b.*, COUNT(v.b_id) AS b_count
FROM
banners_dynamic b
LEFT JOIN banner_views v ON v.b_id = b.id
AND v.b_date >= DATE_ADD(NOW(), INTERVAL - 7 DAY)
WHERE
b.static_keywords LIKE '%test%'
AND b.`status` = '1'
AND b.static_type = '1'
GROUP BY
v.b_id
ORDER BY
b_count ASC
LIMIT 3;

MySQL display team standings from results table

I have two tables:
teams
---------------------
team_id team_name
---------------------
1 Lakers
2 Clippers
3 Grizzlies
4 Heat
results
...............................................................
game_id team_id1 team_id2 team1_score team2_score
1 1 2 20 30
2 1 3 40 50
3 2 1 50 60
4 4 2 20 30
5 1 2 20 30
My question is, how can I then create standings results for this tables based on results sorted by points, like this:
...............................................................
Position team_name total_points games_played
1 Lakers 140 4
2 Clippers 110 3
3 Grizzlies 50 1
4 Heat 20 1
I guess what you would like to do is something like this:
EDITED
SET #num :=0;
SELECT (#num := #num + 1) as Position,team_name,total_points,games_played
FROM (
SELECT teams.team_name, SUM(p) as total_points, count(*) as games_played
FROM (
SELECT team_id1 as id, team1_score as p FROM results
UNION ALL
SELECT team_id2 as id, team2_score as p FROM results
) t
INNER JOIN teams ON t.id = teams.team_id
GROUP BY id,teams.team_name ) t2
ORDER BY total_points DESC;
SQLFiddle is here : http://www.sqlfiddle.com/#!2/5bf2c/1
If you would like to display all teams, even if some teams did not play a single game, you could go like this:
SET #num :=0;
SELECT (#num := #num + 1) as Position,team_name,total_points,games_played
FROM (
SELECT
teams.team_name,
SUM(p) as total_points,
SUM(f) as games_played
FROM (
SELECT team_id1 as id, team1_score as p, 1 as f FROM results
UNION ALL
SELECT team_id2 as id, team2_score as p, 1 as f FROM results
UNION ALL
SELECT team_id as id, 0 as p, 0 as f FROM teams
) t
INNER JOIN teams ON t.id = teams.team_id
GROUP BY id,teams.team_name ) t2
ORDER BY total_points DESC;
SQLFiddle is here: http://www.sqlfiddle.com/#!2/8ecf5d/9
Hope this helps.
I may have renamed a couple of your columns... oh, and teams 1 and 2 are tied so you need to say a little more about how to resolve that...
SELECT t.*
, COUNT(*) p
, SUM(score) pts
FROM
(
SELECT home_team_id team_id,home_team_score score FROM results
UNION ALL
SELECT away_team_id,away_team_score FROM results
) x
JOIN teams t
ON t.team_id = x.team_id
GROUP
BY t.team_id
ORDER
BY pts DESC;
select team_id,team_name,sum(sc1) ,sum(ct1) from
(select team_id,teams.team_name,sc1,ct1 from
(select team_id1,sum(team1_score)as sc1,count(team_id1) as ct1 from results group by team_id1) as srtbl1,teams
where srtbl1.team_id1 =teams.team_id
union
select team_id,teams.team_name,sc2,ct2 from
(select team_id2,sum(team2_score)as sc2 ,count(team_id2) as ct2 from results group by team_id2) as srtbl2,teams
where srtbl2.team_id2 =teams.team_id) sctbl
group by team_id;
and I think you make a mistake in calculating .

Categories