Limit SQL Results to one result per pkey searched using "in" [duplicate] - mysql

This question already has answers here:
Retrieving the last record in each group - MySQL
(33 answers)
Fetch the rows which have the Max value for a column for each distinct value of another column
(35 answers)
Closed 8 years ago.
I have a history table which I would like to use to find the latest user in which updated specific items. Here is the query I have so far:
SELECT *
FROM `history`
WHERE `pKey`
IN ( 13309, 13311, 13951, 14244, 1500, 15558, 15691, 15938, 9769 )
ORDER BY `history`.`time` DESC
LIMIT 0 , 30
This returns multiple history results for each pkey. Is there a way to limit the results to only the latest (based on time) entry from the specific pkey?
So for example:
Right now pkey 13309 has multiple results returned. The query should only return the latest result for it. Same goes for 13311... etc.

This should do:
SELECT h.*
FROM `history` as h
INNER JOIN (SELECT `pkey`, MAX(`time`) as MaxTime
FROM `history`
WHERE `pkey` IN (13309, 13311, 13951, 14244, 1500,
15558, 15691, 15938, 9769)
GROUP BY `pkey`) as t
ON h.`pkey` = t.`pkey`
AND h.`time` = t.`MaxTime`

this should work. Just grouping all the rows that have the same pkey. I think this will work. Comment with a feedback.
Select * from (
SELECT *
FROM `history`
WHERE `pKey`
IN ( 13309, 13311, 13951, 14244, 1500, 15558, 15691, 15938, 9769 )
ORDER BY `history`.`time` DESC) as t1 group by pKey

Related

Get Top 5 latest records for different IDs in SQL [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 2 months ago.
I have a table named Work_Items like this:
Assume there are lots of Names (i.e., E,F,G,H,I etc.,) and their respective Date and Produced Items in this table. It's a massive table, so I'd want to write an optimised query.
In this, I want to query the latest A,B,C,D records.
I was using the following query:
SELECT * FROM Work_Items WHERE Name IN ('A','B','C','D') ORDER BY Date DESC OFFSET 0 LIMIT 4
But the problem with this query is, since I'm ordering by Date, the latest 4 records I'm getting are:
I want to get this result:
Please help me in modifying the query. Thanks.
On MySQL 8+, we can use ROW_NUMBER:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Date DESC) rn
FROM Work_Items
WHERE Name IN ('A', 'B', 'C', 'D')
)
SELECT Name, Date, ProducedItems
FROM cte
WHERE rn = 1
ORDER BY Name;
You can use inner join as follows, its working on any mysql version:
select w.name, w.`date`, w.ProducedItems
from _Work_Items w
inner join (
select name, max(date) as `date`
from _Work_Items
group by name
) as s on s.name = w.name and s.`date` = w.`date` ;

How To Get the first row of each group by [duplicate]

This question already has answers here:
Retrieving the last record in each group - MySQL
(33 answers)
Get top n records for each group of grouped results
(12 answers)
Closed 3 months ago.
I have created a table that has category id and a name and the table contains multiple matching category id so i would like to get the first data of each matching category id
based on the example table above i would like to get just the name alex and brown
Here is what i have tried
SELECT * FROM tailors
WHERE id IN(
SELECT min(id)
FROM tailors
GROUP BY cat_id,id,name,status
)
but i am getting all the record when i am just trying to get the first data of each matching category id
You just need to take out id and name from your group by clause -
SELECT * FROM tailors
WHERE id IN (SELECT min(id)
FROM tailors
GROUP BY cat_id, status
);
If the logic remains same throughout the table, and the version of the DB is 8.0+, then use such an aggregation :
SELECT name
FROM( SELECT t.*, MIN(id) OVER (PARTITION BY cat_id) AS min
FROM tailors AS t ) AS tt
WHERE id = min
assuming id is a primary key column, there will be only one minimum value per each cat_id.
GROUP BY cat_id is handled by PARTITION BY cat_id and the other columns(name and status) following it should be removed.
To return only one row use LIMIT 1:
SELECT * FROM tailors
WHERE id IN(
SELECT min(id)
FROM tailors
GROUP BY cat_id,id,name,status
) LIMIT 1

How to display the latest Record [duplicate]

This question already has answers here:
Select last row in MySQL
(11 answers)
Closed 2 years ago.
I want to display only the latest record from usersId.
How do I create a query that would give me the latest ordersId from usersId?
The table looks like this:
this the query that I use but it displays all the ordersId:
SELECT * FROM `orders` WHERE usersId=?
You can use the LIMIT clause as follows:
SELECT * FROM `orders` WHERE usersId=?
order by orderdate desc limit 1;
OR you can use analytical function row_number as follows:
select * from
(SELECT t.*,
row_number() over (partition by usersId order by orderdate desc) as rn
FROM `orders` t WHERE usersId=?) t
where rn = 1
row_number solution is useful when you want the latest data for multiple usersid.
To get the latest one record, please
set order by OrdersID in descending order, and then
get only 1 record by using "limit 0, 1"
So please change the
SELECT * FROM `orders` WHERE usersId=?
to
SELECT * FROM `orders` WHERE usersId=? order by ordersId desc limit 0,1
You are binding $uid before setting it to the user_id from session you should assign first & then bind.
$uid=$_SESSION['userid'];
$stmt->bind_param("s",$uid);

Query is returns the wrong value for row [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 2 years ago.
I have the following query.
SELECT MAX(activity_id), group_id, parent_group_id FROM dashboard_activity_detail WHERE account_id = 8997 AND parent_group_id IN (5118,5026,4522,3983,3586,3278,3227) AND activity_type_id = 18 GROUP BY parent_group_id;
My expectation is that the group_id will be returned associated with the largest activity_id. There are multiple rows with the same parent_group_id in the table. What I get back is a value from a different row. The activity_id is correct and the parent_group_id is correct but I get a value from a different row for the group_id.
What am I missing? I've tried order by and various other methods with the same result.
You expectation is wrong. You query is malformed because the SELECT columns are inconsistent with the GROUP BY columns.
Use window functions (available in MySQL 8+):
SELECT da.*
FROM (SELECT da.*,
ROW_NUMBER() OVER (PARTITION BY parent_group_id ORDER BY activity_id DESC) as seqnum
FROM dashboard_activity_detail da
WHERE account_id = 8997 AND
parent_group_id IN (5118,5026,4522,3983,3586,3278,3227) AND
activity_type_id = 18
) da
WHERE seqnum = 1;

Select first row for each different column value [duplicate]

This question already has answers here:
Get records with max value for each group of grouped SQL results
(19 answers)
Closed 5 years ago.
Having a table T like this:
ID DateTime asha
AF35 15-01-17 af
AF35 14-01-17 la
AF35 13-01-17 fi
DF57 15-01-17 sk
DF57 14-01-17 sj
DG36 15-01-17 be
DG36 14-01-17 dh
What is the simplest mysql query to have only first row for each unique ID returned, being ordered by the most recent DateTime?
I the expected result would be something like this:
ID DateTime asha
AF35 15-01-17 af
DF57 15-01-17 sk
DG36 15-01-17 be
I tried SELECT * FROM T GROUP BY ID ORDER BY DateTime, however, mysql returns an error for not adding the other columns to the clause. And if I add them, I still get duplicated results for the ID.
My favorite method to write this query is with a not exists clause:
select *
from T as t1
where not exists (
select 1
from T as t2
where t2.ID = t1.ID
and t2.DateTime > t1.DateTime
)
SELECT Distinct(ID),DateTime,asha FROM T GROUP BY ID ORDER BY DateTime desc
use above query to unique Id records.