I am trying to do a MYSQL query where I get the most recent purchase for a user and then see if falls within certain criteria. Here is the query I put together:
select
users_purch.purch_date as purchase_date,
users_purch.total_amount as purchase_amount,
users.*
from
users
left join
(
select
max(date) as purch_date,
user_id,
total_amount
from
users_purchases
group by
user_id
) as users_purch
on users_purch.user_id = users.id
where
users_purch.purch_date < '2016-11-01'
and users_purch.total_cost < 112.49
order by
users_purch.purch_date desc
It seems that the query works but fails in certain aspects. For example, if a user has more than one purchase entry it is getting the max date but the amount as total_cost that the query retrieves is not from the same row as the max date. How can I rewrite this query to give me the most recent purchase record in its entirety?
Thanks!
You have to join once more to user_purchases table in order to get the information about the date:
select
users_purch.purch_date as purchase_date,
users_purch.total_amount as purchase_amount,
users.*
from
users
left join
(
select
max(date) as purch_date,
user_id
from
users_purchases
group by
user_id
) as users_purch
on users_purch.user_id = users.id
left join
(
select
user_id,
date,
total_amount
from
users_purchases
) as users_purch2 on users_purch.user_id = users_purch2.user_id and
users_purch2.date = users_purch.purch_date
where
users_purch.purch_date < '2016-11-01'
and users_purch.total_cost < 112.49
order by
users_purch.purch_date desc
due the group by you have in this select
if you need the amount of the max(date) rewrite extecting the proper amount
select
users_purch.purch_date as purchase_date,
users_purch.total_amount as purchase_amount,
users.*
from
users
left join
(
select t1.purch_date, t1.user_id, t2.total_amount from (
select
max(date) as purch_date,
user_id
from users_purchases
group by user_id ) t1
inner join (
date,
user_id,
total_amount
from users_purchases
) t2 on t1.user_id= t2.user_id, t1.purch_date = t2.date
) as users_purch
on users_purch.user_id = users.id
where
users_purch.purch_date < '2016-11-01'
and users_purch.total_cost < 112.49
order by
users_purch.purch_date desc
You can try this one, mate:
SELECT
up.date AS 'purchase_date',
up.total_amount AS 'purchase_amount',
u.*
FROM
users u
INNER JOIN users_purchases up ON up.user_id = u.user_id
INNER JOIN (
# get max date per user_id
SELECT user_id, max(date) AS 'purch_date'
FROM users_purchases
GROUP BY user_id
) max_up ON
max_up.user_id
# join that date to get the correct total_amount
AND max_up.`purch_date` = up.`date`
WHERE
up.`date` < '2016-11-01'
AND up.total_amount < 112.49
GROUP BY u.user_id
ORDER BY up.`date` DESC;
Note
Max Date per user_id
Value of total_amount per Max Date
Grouped per user_id
Ordered descending using users_purchases.date
Related
I have two separate table LPG_usage and devices.
In the LPG_usage table has 5 columns as (Device_id,Cylinder_Type,Date,Kg,Data_index ) and the devices table has 3 columns as (Device_id,User_name,Location)
I want to select newest record by considering the Date in the LPG_usage table for all of Device_id's with the Location at the device table. The selected table include (Device_id,Cylinder_Type,Date,Kg,Location)
I made a query for that but it getting error as unknown column 'td.Device_id' in 'on clause'
my code as following
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
INNER JOIN (
SELECT Location FROM devices
)td on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate and t.Device_id = td.Device_id
I would be really grateful for any help,Thank you
Your error message is because your td subquery does not have device_id. You can add it by changing SELECT Location FROM devices to SELECT device_id, Location FROM devices. You will also need to move some of your conditions in the on for the join to td to a new on for the join to tm.
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate
INNER JOIN (
SELECT device_id, Location FROM devices
)td
on t.Device_id = td.Device_id
The above should work, but it's not clear to me why you have the subquery for td. I would suggest considering:
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate
INNER JOIN devices td
on t.Device_id = td.Device_id
Another alternative to consider on modern DBs is:
SELECT device_id, data, kg, cylinder_type, location
FROM
(
select t.Device_id, t.Date, t.Kg, t.Cylinder_Type, td.Location, RANK() OVER(PARTITION BY t.device_id ORDER BY t.data DESC) rk
from lpg_usage t INNER JOIN devices td
on t.Device_id = td.Device_id
)
WHERE rk = 1
The inner query uses a window function (RANK) to number the results in a given order (t.date DESC) for each device_id. The outer query uses that to only get the maximum date for each device_id. This uses RANK so it will return multiple rows for ties (like your original query). You could use ROW_NUMBER if you prefer to only get one record when there is a tie by date.
I have a big data problem with MySQL.
I have:
a users table with 59033 rows, and
a user_notes table with 8753 rows.
But when I search which users have user note in some dates.
My query like this :
SELECT u.*, rep.name as rep_name FROM users as u
LEFT JOIN users as rep on rep.id = u.add_user
LEFT JOIN authorization on authorization.id = u.authorization
LEFT JOIN user_situation_list on user_situation_list.user_situation_id = u.user_situation
WHERE
EXISTS(
select * from user_notes
where user_notes.note_user_id = u.id AND user_notes.create_date
BETWEEN "2017-10-20" AND "2017-10-22"
)
ORDER BY u.lp_modify_date DESC, u.id DESC
Turn it around -- find the ids first; deal with the joins later.
SELECT u.*,
( SELECT rep.name
FROM users AS rep
WHERE rep.id = u.add_user ) AS rep_name
FROM (
SELECT DISTINCT note_user_id
FROM user_notes
WHERE create_date >= "2017-10-20"
AND create_date < "2017-10-20" + INTERVAL 3 DAY
) AS un
JOIN users AS u ON u.id = un.note_user_id
ORDER BY lp_modify_date DESC, id DESC
Notes
No GROUP BY needed;
2 tables seem to be unused; I removed them;
I changed the date range;
User notes needs INDEX(create_date, note_user_id);
Notice how I turned a LEFT JOIN into a subquery in the SELECT list.
If there can be multiple rep_names, then the original query is "wrong" in that the GROUP BY will pick a random name. My Answer can be 'fixed' by changing rep.name to one of these:
MAX(rep.name) -- deliver only one; arbitrarily the max
GROUP_CONCAT(rep.name) -- deliver a commalist of names
Rewriting your query to use a JOIN rather than an EXISTS check in the where should speed it up. If you then group the results by the user.id it should give you the same result:
SELECT u.*, rep.name as rep_name FROM users as u
LEFT JOIN users as rep on rep.id = u.add_user
LEFT JOIN authorization on authorization.id = u.authorization
LEFT JOIN user_situation_list on user_situation_list.user_situation_id = u.user_situation
JOIN user_notes AS un
ON un.note_user_id
AND un.create_date BETWEEN "2017-10-20" AND "2017-10-22"
GROUP BY u.id
ORDER BY u.lp_modify_date DESC, u.id DESC
I'm trying to create a leaderboard but i'm not sure how to do the mysql query.
I would like to count all the levels from a player in the skills table and get the total Level and count all the experience from a player in the experience table and get the Total Exp along with displaying the persons name from the users column.
There is 3 tables factions_mcmmo_users, factions_mcmmo_experience, factions_mcmmo_skills.
This is what i have so far but it doesn't work:
$sql = ("SELECT a.id,
(SELECT COUNT(*) FROM factions_mcmmo_experience WHERE user_id = a.id) as TotalXP,
(SELECT COUNT(*) FROM factions_mcmmo_skills WHERE user_id = a.id) as TotalLevel
FROM (SELECT DISTINCT id FROM factions_mcmmo_users) a LIMIT 10;");
Any help would be very appreciated
EDIT: I have it working now but i'm unsure if its the most efficient way to do things so if anyone could help me out if theres a better way, it would mean a lot.
I would also like to know if it's possible to display the total exp and level with commas if the number is in the thousands for example: total level 5,882 and total xp 582,882
EDIT 2:
I have figured out how to format the numbers but still don't know if my code is efficient
$sql = ("SELECT id, user,
(SELECT FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy),0) FROM factions_mcmmo_skills b WHERE b.user_id = a.id) as TotalLevel,
(SELECT FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy),0) FROM factions_mcmmo_experience c WHERE c.user_id = a.id) as TotalXP
FROM (SELECT id, user FROM factions_mcmmo_users) a group by id ORDER BY TotalLevel DESC, TotalXP DESC LIMIT 10;");
EDIT 3
Updated code from scaisEdge but was displaying everyones level as 1 and XP as 1, so i changed count(*) changed to sum, added an order By TotalLevel in Descending order and that seems to have worked but i can't get it to display the persons name (user column) in the user table? not sure if i was supposed to change to sum because it didn't work the other way.
$sql = ("SELECT a.id, b.TotalXP, c.TotalLevel
FROM (SELECT DISTINCT id FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
ORDER BY TotalLevel DESC
LIMIT 10;");
EDIT 4
Everything working but when i try to format the totals using "FORMAT(Sum(Columns), 0) on the inner joins, the EXP Total appears to work but the main Total Level is not displaying results that are over 1,000 and it breaks the leaderboard positioning, it should be sorting them on total level but it appears to be random, when u remove the format,0 it goes back to working
I would like it to display commas if the number number is the thousands for example: Total Level: 5,532 and Total EXP 5882,882
See live demo: http://mcbuffalo.com/playground/leaderboards/server/factions-mcmmo.php
Updated Code trying to use Format:
$sql = ("SELECT a.id, a.user, b.TotalXP, c.TotalLevel
FROM (SELECT id, user FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy), 0) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy), 0) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
ORDER BY TotalLevel DESC;");
EDIT 5
Changed number with PHP, everything works
Original Images
you could use an couple of inner join
$sql = ("SELECT a.id, a.name, b.TotalXP, c.TotalLevel
FROM (SELECT DISTINCT id, name FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, COUNT(*) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, COUNT(*) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
LIMIT 10
In my mysql query, I try to get all threads with their most recent row.
$query = "SELECT th.id, tm.message, tm.date_sent, tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN thread_message tm ON th.id=tm.thread_id
JOIN (
SELECT thread_id, MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id AND tm.date_sent = q.date_sent
ORDER BY tm.date_sent DESC";
This works, but the problem is, if there is two or more rows who's date is the most recent and they are the same date, then it will join with both of them. I need that third join statement to join with at most 1 row.
I also don't want to assume that the biggest id implies its the most recent row, because I could always change the dates manually later.
Does anyone know how to fix this?
Thanks
One way to do this is to establish a row number per group, in this case your group is thread_id and date_sent. With MySql, you need to use user-defined variables to do this:
SELECT th.id,
tm.message,
tm.date_sent,
tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN (
SELECT id,
thread_id,
message,
date_sent,
#rn:=IF(#prevthread_id=thread_id, #rn+1, 1) rn,
#prevthread_id:=thread_id
FROM thread_message, (SELECT #rn:=1, #prevthread_id:=0) t
ORDER BY thread_id, date_sent DESC, id
) tm ON th.id=tm.thread_id
AND tm.rn = 1
ORDER BY tm.date_sent DESC
Perhaps this is easier for you (but only because you're using mysql):
SELECT th.id,
tm.message,
tm.date_sent,
tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN thread_message tm ON th.id=tm.thread_id
JOIN (
SELECT thread_id,
id,
MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id
AND q.id = tm.id
AND tm.date_sent = q.date_sent
ORDER BY tm.date_sent DESC
This will return an arbitrary id to join on.
Seems to me that if the query produces what you expect, with exception of the last JOIN you can just modify the GROUP BY which will only return one row.
JOIN (
SELECT thread_id, MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id AND tm.date_sent = q.date_sent
GROUP BY tm.date_sent
ORDER BY tm.date_sent DESC";
This is my existing query:
$query = mysql_query("SELECT s.*,
UNIX_TIMESTAMP(`date`) AS `date`,
f.userid as favoritehash FROM songs s
LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash'
ORDER BY s.date DESC");
It gathers all my songs and the associated favorite information from my db.
This is a basic pagination query that returns values from my db by groups of days:
$query = mysql_query("
select * from songs t1 join (
select to_days(date) day from songs
group by day
order by day desc
limit $start_row, $items_per_page
) t2
on to_days(t1.date) = t2.day
order by day desc") or die(mysql_error());
Here is the column info for the two tables songs and favorites
Songs:
Favorites:
The correlation between favorites and songs is pretty simple where the favorite value in favorites holds the unique id of the song it is a favorite of.
My question is how would I combine these two queries so as to return all the information in the original query but grouped and paginated as it is in the second query?
SELECT B.*
FROM favorites as A
JOIN (
select * from songs t1 join (
select to_days(date) day from songs
group by day
order by day desc
limit $start_row, $items_per_page
) t2
on to_days(t1.date) = t2.day
order by day desc
) as B
ON A.Favorite = B.ID
ORDER BY B.DAY, B.ID
I don't use MySQL and not familiar with using the "limit", but this script might work. The LEFT JOIN with favorites should not increase the row count and append the columns. Would the "limit" work on the outer script also?
select s.*,UNIX_TIMESTAMP(`date`) AS `date`, f.userid as favoritehash
from songs s
join (
select to_days(date) day
from songs
group by to_days(date)
order by day desc
limit $start_row, $items_per_page
) s2 on to_days(s.date) = s2.day
LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash'