I have two tables:
users:
user_id user_name
data:
user_id user_data user_time
I wan to select the latest entry from the data table, but return the user_name, user_id, user_data and user_time.
I have tried the following query, but it returns the first entry, not the last for each user:
sql = "SELECT users.user_name, users.user_id, data.user_data, data.user_time
FROM users
INNER JOIN data ON data.user_id = users.user_id
GROUP BY users.user_name
ORDER BY data.user_time DESC";
Use GROUP BY and MAX, WHERE...IN:
SELECT u.user_id, u.user_name, d.user_data, d.user_time
FROM users u
INNER JOIN data d ON d.user_id = u.user_id
WHERE (d.user_id, d.user_time) =
(SELECT user_id, MAX(user_time) FROM data GROUP BY user_id)
I think you had better add data_id column to data table.
Unless data_id, both user_id and user_time are necessary for PRIMARY KEY(and user_time is not always unique, not reliable)
If there is data_id, it can be bitly simple:
SELECT u.user_id, u.user_name, d.user_data, d.user_time
FROM users u
INNER JOIN data d ON d.data_id =
(SELECT data_id FROM data
WHERE user_id = u.user_id ORDER BY data_time DESC LIMIT 1)
Related
I have two tables
users: id, email, firstName, lastName
subscriptions: id, userId, currentPeriodStart, currentPeriodEnd
Below just shows you how the two tables are related. I want to return subscriptions that expire after 1565827199, but it needs to check against each user's most recent subscription.
select
u.id
from users u
join subscriptions s on u.id s.userId
where s.currentPeriodEnd > 1565827199
ORDER BY u.lastName ASC
A user may have multiple subscriptions in the subscriptions table. What I need to do is modify the query above, so it checks against that user's most recent subscription and not the first one it finds.
select * from subscriptions ORDER BY currentPeriodEnd DESC LIMIT 1
I've tried a few different things (alias table, sub query) I found elsewhere on stackoverflow without any luck.
You can filter with a correlated subquery, like so:
select u.*, s.*
from users u
inner join subscriptions s on u.id = s.userId
where s.currentPeriodEnd = (
select max(s1.currentPeriodEnd)
from subscriptions s1
where s1.userId = u.id and s1.currentPeriodEnd > 1565827199
)
order by u.lastName
For performance, consider an index on subscriptions(userId, currentPeriodEnd).
Alternatively, if you are running MySQL 8.0, you can use row_number():
select *
from (
select
u.*,
s.*,
row_number() over(partition by u.id order by s.currentPeriodEnd desc)
from users u
inner join subscriptions s on u.id = s.userId
where s.currentPeriodEnd > 1565827199
) t
where rn = 1
order by lastName
Join with a subquery that gets the latest time for each user, and filters it down to just the ones after your specified timestamp.
select u.id
from users u
join (
select userid
FROM subscriptions
GROUP BY userid
HAVING MAX(currentPeriodEnd) > 1565827199
) s ON s.userid = u.id
ORDER BY u.lastName ASC
i have the table "user" (Primary key is id) and the table "user_meta" (Primary key is user_id and valid_from).
The user table contains basic user data e.g. username, password, etc.
The user_meta contains possible changing data e.g. lastname, gender(yea its 2018 :D) etc.
So i have a history on which day which data are valid.
My Problem ist that i try to select all user with the currently valid data, but i failed often...
How i can select the correct data ?
For one user i can simply use
"select * from user_meta
JOIN user on user_meta.user_id = user.id
ORDER BY valid_from DESC LIMIT 1"
but how its working with multiple/all users?
greetings,
False
you could use a join on a subselect for max_valid group by user
select * from user_meta
inner join (
select user.id, max(user_meta.valid_from) max_valid
from user_meta
JOIN user on user_meta.user_id = user.id
group by user.id
) t on t.id= user_meta.user_id and t.max_valid = user_meta.valid_from
or more simple
select * from user_meta
inner join (
select user_meta.user_id, max(user_meta.valid_from) max_valid
from user_meta
group by user_meta.user_id
) t on t.user_id= user_meta.user_id and t.max_valid = user_meta.valid_from
You probably want something along these lines:
SELECT u.*, um.*
FROM user u
INNER JOIN user_meta um
ON u.id = um.user_id
INNER JOIN
(
SELECT user_id, MAX(valid_from) AS max_valid_from
FROM user_meta
GROUP BY user_id
) t
ON um.user_id = t.user_id AND
um.valid_from = t.max_valid_from;
Not much to explain here, except that the subquery aliased as t will filter off all metadata records except for the latest one, for each user.
I have 3 tables like so
Table 1: UserInfo
user_id userName
123 userOne
Table 2: Post
user_id postContent
123 This is test message
Table 3: LikePost
user_id likesPostId
123 This is test message
I would like to run a query to get total number of post likes, posts, and user information from those 3 tables.
I can do this for each one such as in Post table:
SELECT COUNT(*) FROM Post WHERE Post.user_id = '123'
and SELECT * FROM UserInfo WHERE UserInfo.user_id = '123'
Is anyone have better solution in just 1 query? Thank you so much!
Use a structured query (with subqueries) something like this.
SELECT u.user_id, u.userName, p.num postcount, l.num likecount
FROM UserInfo u
LEFT JOIN (
SELECT COUNT(*) num,
user_id
FROM Post
GROUP BY user_id
) p ON u.user_id = p.user_id
LEFT JOIN (
SELECT COUNT(*) num,
user_id
FROM LikePost
GROUP BY user_id
) l ON u.user_id = l.user_id
What's going on here? The two subqueries, for example
SELECT COUNT(*) num,
user_id
FROM LikePost
GROUP BY user_id
each generate a virtual table with either zero or one row per user_id, showing a count for each user_id. You then join those virtual tables to your UserInfo table.
Use LEFT JOIN because ordinary innner JOIN will suppress users that lack either posts or likes.
Try This
SELECT ui.userName,Count(p.*),
Count(lp.*) as TotalPostLikes
FROM UserInfo ui
INNER JOIN Post p on p.user_id=ui.user_id
INNER JOIN LikePost lp on lp.user_id=ui.user_id
WHERE ui.user_id = '123'
GROUP BY ui.userName
If you want to select Username, Post and Likes on post, try the following
SELECT ui.userName,p.postContent as PostContent,
(SELECT COUNT(lp.user_id) FROM LikePost lp
WHERE lp.user_id=ui.user_id) as Likes,
(SELECT COUNT(_p .user_id) FROM Post _p
WHERE _p .user_id=ui.user_id) as TotalPosts
FROM UserInfo ui
INNER JOIN Post p on p.user_id=ui.user_id
WHERE ui.user_id = '123'
Yes you can do it within one query using leftjoin on Post and LikePost like below
SELECT COUNT(*),User.userName FROM UserInfo as User
leftjoin Post as Post on Post.user_id = User.user_id
leftjoin LikePost as LikePost on LikePost.user_id = User.user_id
where Post.user_id = 123
group by Post.user_id
One table is Users with id and email columns.
Another table is Payments with id, created_at, user_id and foo columns.
User has many Payments.
I need a query that returns each user's email, his last payment date and this last payment's foo value. How do I do that? What I have now is:
SELECT users.email, MAX(payments.created_at), payments.foo
FROM users
JOIN payments ON payments.user_id = users.id
GROUP BY users.id
This is wrong, because foo value does not necessarily belong to user's most recent payment.
Try this :
select users.email,foo,create_at
from users
left join(
select a.* from payments a
inner join (
select id,user_id,max(create_at)
from payments
group by id,user_id
)b on a.id = b.id
) payments on users.id = payments.user_id
If users has no payment yet, then foo and create_at would return NULL. if you want to exclude users who has no payment, then use INNER JOIN.
One approach would be to use a MySQL version of rank over partition and then select only those rows with rank = 1:
select tt.email,tt.created_at,tt.foo from (
select t.*,
case when #cur_id = t.id then #r:=#r+1 else #r:=1 end as rank,
#cur_id := t.id
from (
SELECT users.id,users.email, payments.created_at, payments.foo
FROM users
JOIN payments ON payments.user_id = users.id
order by users.id asc,payments.created_at desc
) t
JOIN (select #cur_id:=-1,#r:=0) r
) tt
where tt.rank =1;
This would save hitting the payments table twice. Could be slower though. Depends on your data!
There are three tables. user, like, comment. Table like and comment has rows associated to user. I need all users with their associated row count from table like and comment. It's easy to do when there is only one table associated. However, here is my query.
SELECT u.id as id, u.display_name as displayName,
COUNT(x.user_id) as likeCount,
COUNT(y.user_id) as commentCount
FROM `user` u
LEFT JOIN
`like` x ON x.user_id = u.id
LEFT JOIN
`comment` y ON y.user_id = u.id
GROUP BY u.id
Table relationships:
One user has many likes
One user has many comments
commentCount is giving correct rows count, but likeCount giving wrong rows count. Please don't post answer which uses sub queries. I want it with only ONE SELECT clause. I am using MySQL. TIA
You can get the user count per individual table, like this:
SELECT user, COUNT(*) AS t1Count
FROM table1
GROUP BY user;
SELECT user, COUNT(*) AS t2Count
FROM table2
GROUP BY user;
Then you can join those two to the Users table to get the count of each. You should use COALESCE() to return null values with 0:
SELECT u.id, COALESCE(t1.t1Count, 0), COALESCE(t2.t2Count, 0)
FROM users u
LEFT JOIN(
SELECT user, COUNT(*) AS t1Count
FROM table1
GROUP BY user) t1 ON u.id = t1.user
LEFT JOIN(
SELECT user, COUNT(*) AS t2Count
FROM table2
GROUP BY user) t2 ON u.id = t2.user;
Here is an SQL Fiddle example.