简体   繁体   中英

MySQL queries to get latest result plus number of records

I am struggling with getting the latest record by ID and its amount of records with the same values.

My first MySQL query is:

SELECT COUNT(*) AS Total FROM `users` 
WHERE status = '1' AND option1 = {variable from URL}
AND option2 = '1'

Which shows amount of records fine. And my second query is:

SELECT option1, option2
FROM `users` WHERE date IN (SELECT MAX(date) FROM `users` 
WHERE option1 = '2' GROUP BY option2) ORDER BY date DESC

It works fine too.

Is there any way to have merge this two requests in one? Or I'm supposed to send 2 different queries?

My table looks like:

option1  |  option2  |  status  |
1        |  2        |  1       |
2        |  1        |  2       |
1        |  2        |  2       |
6        |  1        |  1       |
1        |  2        |  1       |

Or I need to use a PHP solution to achieve this? And I want to get results as:

option1  |  option2  |  status  | Total  |
1        |  2        |  1       | 2      |
2        |  1        |  2       | 0      |
1        |  2        |  2       | 0      |
6        |  1        |  1       | 1      |

May be not the nicest, but how about two users tables:

SELECT COUNT(u1.option1) AS Total, u2.option1, u2.option2
  FROM `users` u1, `users` u2
 WHERE u1.status = '1' 
   AND u1.option1 = {variable from URL}
   AND u1.option2 = '1'
   AND u2.date IN (SELECT MAX(date) 
                    FROM `users` 
                    WHERE option1 = '2' 
                    GROUP BY option2) ORDER BY u2.date DESC;

Depends a bit on how many records you expect.

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