I have a table with more than 50k entries and a few users:
transactions Table:
ID
USER
VALUE
TIMESTAMP
users Table:
USER
TYPE
REGION
I would like to get the most recent transactions for each user. So far I am using the following GROUP BY statement, but it is slow (takes 5-10sec approx):
select ID , max(TIMESTAMP) as TIMESTAMP from transactions group by USER;
Is there a faster statement to retrieve the most recent entries?
First of all as per my understanding ID columns should keep unique values in transaction table so group by should be on USER field as per your requirement.
Further you can try below query. I am not sure but you can compare its time with your query and use accordingly.
SELECT
USER , TIMESTAMP
FROM
(SELECT USER,TIMESTAMP FROM transactions ORDER BY ID DESC) a
GROUP BY USER;
Assuming there will be an index on USER column as this is common between both tables.
Try this,
select u.*,tr.* from users as u
outer apply
(
select top 1 * from transactions as t
where t.USER= u.USER
order by t.ID desc
)as tr
Related
I would like to delete my MySQL selection.
Here is my MySQL selection request:
SELECT *
FROM Items
WHERE id_user=1
ORDER
BY id_user
LIMIT 2,1
With this working request, I select the third item on my table which has as id_user: 1.
Now, I would like to delete the item that has been selected by my request.
I am looking for a same meaning request which would look like this :
DELETE FROM Items (
SELECT * FROM Items WHERE id_user=1 ORDER BY id_user LIMIT 2,1
)
The first thing to note is that there is an issue with your query. You are filtering on a unique value of id_user and sorting on the same column. As all records in the resultset will have the same id_user, the actual order of the resultset is undefined, and we cannot reliably tell which record comes third.
Assuming that you have another column to disanbiguate the resultset (ie some value that is unique amongst each group of records having the same id_user), say id, here is a solution to your question, that uses a self-join with ROW_NUMBER() to locate the third record in each group.
DELETE i
FROM items i
INNER JOIN (
SELECT
id,
id_user,
ROW_NUMBER() OVER(PARTITION BY id_user ORDER BY id) rn
FROM items
) c ON c.id = i.id AND c.id_user = i.id_user AND c.rn = 3
WHERE i.id_user=1 ;
Demo on DB Fiddle
You didn't provide the definition of your table. I guess it has a primary key column called id.
In that case you can use this
CREATE TEMPORARY TABLE doomed_ids
SELECT id FROM Items WHERE id_user = 1 ORDER BY id_user LIMIT 2,1;
DELETE FROM Items
WHERE id IN ( SELECT id FROM doomed_ids);
DROP TABLE doomed_ids;
It's a pain in the neck, but it works around the limitation of MySQL and MariaDB disallowing LIMITs in ... IN (SELECT ...) clauses.
You can use the select query to create a derived table and join it back to your main table to determine which record(s) to delete. Derived tables can use the limit clause.
Assuming that the PK is called id, the query would look as follows:
delete i from items i
inner join (SELECT id FROM Items
WHERE id_user=1
ORDER BY id_user LIMIT 2,1) i2 on i.id=i2.id
You need to substitute your PK in place of id. If you have a multi-column PK, then you need to select all the PK fields in the derived table and join on all of them.
I have a table "users" which has multiple columns in which column "status" has multiple values like 1,0,3,2,4. There is column "user_id" which doesn't contain unique values since, this is foreign key of another table called "user_master".
so here in "users" table we have multiple values of the one user.
So, Here is my actual query is that i would like to write a sql query to find users has only one entry in table "users" with particular status value.
For e.g. I would like to fetch all such users with status=2 and their entry in table is not more than 1. Like if user has multiple entries with status 2,1,4 in table which should not be return in query.
It should yield those users which has only one entry in table and which is of status = 2
That must be what you use:
Select count(u.user_id) AS cnt, u.*
from user u
where u.status = 2
group by u.user_id, u.status
having cnt = 1;
WITH tmp AS(
SELECT Stud_Id,COUNT(*) AS 'Count' FROM Student_tbl GROUP BY Stud_Id
)
SELECT * FROM tmp WHERE Count = 1 AND Status = 2
You have to add field in GROUP BY Clause whichever you want to use in SELECT clause.
I have researched it and found answer for it.
And query goes like this.
select count(id) as cnt,
user_id,status from users
group by user_id
having cnt < 2 and status=2
First it will group the things having count less than 2 and then which will check for status.
Table :
I am new to query writing. Now I am stuck on retrieving 2 rows from above table.
Data will be date sorted in descending order for only 2 different topic_id. There won't be a third different topic_id.
So I want to retrieve two rows only that will have different topic_id, one data for each topic_id having most recent date.
The result would be
try sql fiddle
http://sqlfiddle.com/#!2/f37963/9
SELECT t1.* FROM temp t1
JOIN (SELECT question_id, MAX(`date`) as `date` FROM temp GROUP BY topic_id) t2
ON t1.question_id= t2.question_id AND t1.`date`= t2.`date`;
The logic is to find the latest date in each group (subquery) and join it with the table again to retrieve other particulars.
use this
$qry="SELECT * FROM table_name GROUP BY TOPIC_ID ORDER BY DATE desc";
I need to remove all the duplicates and keep only one with the highest amount . Perhaps I should do some kind of JOIN operation but I'm not very experienced with . I have this query :
SELECT *
FROM invoices
GROUP BY user
ORDER BY amount DESC
it queries all the rows, orders them by amount and "removes" the duplicates as it groups by user but obviously doesn't delete the duplicates. Any help is appreciated . To make it clear the duplicates must be deleted permanently.
Schema :
user varchar(125), amount int
If you do a SELECT * that's not going to filter out records, even with a GROUP BY.
SELECT user, MAX(amount) amount
FROM invoices
GROUP BY user
ORDER BY amount DESC
For the sake of just finding duplicates, you can try:
SELECT id, COUNT(amount) AS cnt, MAX(amount) AS mx
FROM invoices
GROUP BY user HAVING cnt > 1
ORDER BY amount DESC
From there, you can proceed removing these records.
Be aware that you won't get the desired result because of the way you're using GROUP BY. MySQL extends it's functionality. You want to always specify the columns being selected in the GROUP BY:
SELECT col1, col2, AGGREGATE(col3)
FROM table
GROUP BY col1, col2
I need to select all the rows find duplicates
To find the MAX amount for each user:
SELECT user,
Max(amount) AS amount
FROM invoices
GROUP BY user
and keep only the row with the highest amount
Option 1
Use a LEFT JOIN (thanks JW):
DELETE invoices
FROM invoices
LEFT JOIN
(SELECT user, MAX(amount) AS amount
FROM invoices
GROUP BY user) j
ON j.user = invoices.user
AND j.amount = invoices.amount
WHERE j.amount IS NULL
http://sqlfiddle.com/#!2/ce2f8/1
Option 2
Create a staging table:
CREATE TABLE invoices (
user int,
amount decimal(5,2));
INSERT INTO invoices VALUES
(1, 100.00),
(1, 200.00),
(1, 300.00);
CREATE TABLE invoicesStg (
user int,
amount decimal(5,2));
INSERT INTO invoicesStg
(SELECT user, MAX(amount) AS amount
FROM invoices
GROUP BY user);
TRUNCATE invoices;
INSERT INTO invoices
SELECT user, amount
FROM invoicesStg;
DROP TABLE invoicesStg;
http://sqlfiddle.com/#!2/0381e/1
If you want the row with the highest amount, try this:
select *
from invoices
order by amount desc
limit 1
I'm not sure what you mean by "delete". Do you really want to delete all rows but the one with the highest amount?
I have two tables, users and events, and I want to select e.g. 6 users from the USERS table and list all of their events in chronological order of the event date
table design:
USERS EVENTS
user_id >>>> user_id
event_title
event_date
Do I select all the events into a temporary table then query that with "order by" or is there a more efficient way to do this within the query itself?
This will select six arbitrary users from your users table and fetch all their events:
SELECT user_id, event_title, event_date
FROM EVENTS
WHERE user_id IN
(
SELECT user_id
FROM USERS
LIMIT 6
)
ORDER BY event_date
You should change the subselect to select six specific users based on your desired criteria, instead of just the first six that MySQL finds.
You should add indexes to ensure that this runs efficiently. Use EXPLAIN SELECT ... to check which indexes are being used.