Reputation: 93
There is a problem with my MySql query. Could you help me out with it?
I have a database as in the picture above, and there are userids that belongs to each user. It should be sorted by type descending. It records the time with the PHP time() function which is written at that moment in the datetime cell within the database. However, the SQL query which I used gives me a result as in the picture below:
SELECT
user.username,
kim.userid,
kim.subject,
count(kim.userid),
max(kim.dateline),
max(kim.rateid)
FROM test as kim
INNER JOIN user
WHERE user.userid = kim.userid
GROUP BY kim.userid limit 10)
Although I get the right results, I’m still having a little problem since the rateid does not show the right subject. So, I’ve been searching for it for two days, and I think there’s a problem that I don't understand or cannot see.
The right query should be like the on in the following picture:
I appreciate if you help!
Upvotes: 2
Views: 240
Reputation: 93
Thanks for attention ,
i found the solution of my problem. The solution should be like this:
SELECT subject FROM test WHERE userid=user.userid ORDER BY dateline desc LIMIT 1) AS subject, (SELECT COUNT(*) FROM test WHERE userid=user.userid) AS adet FROM user limit 10
Upvotes: 0
Reputation: 1270391
You are trying to get information from the line that has the maximum rateid, along with aggregated information. For this, you need to join back to the original table:
select kim.userid, u.username, kim.cnt, kim.maxdate, kim.maxrate, t.subject
from (SELECT kim.userid, count(kim.userid) as cnt,
max(kim.dateline) as maxdate, max(kim.rateid) as maxrate
FROM test kim
GROUP BY kim.userid
limit 10
) kim INNER JOIN
user u
on u.userid = kim.userid join
test t
on kim.userid = t.userid and
kim.maxrate = t.rateid
This finds the maxrate for each user and then joins back to the table to get the subject for that rate. Your maxdate
column seems to be what you want. If you want the date for the maxrate
then you might also want to take it from t
.
Upvotes: 1
Reputation: 2272
try this
Select user.username, kim.userid ,kim.subject, count(kim.userid), max(kim.dateline),
max(kim.rateid)
from test as kim
left join user ON user.userid = kim.userid group by kim.userid limit 10
Upvotes: 0