简体   繁体   中英

Top Comment Sql query

SQLyapısı

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!

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM