How to Group by user_id and order by desc - php

Hello i am aware this is very basic but right now i am so confused i want to GROUP BY user_id ORDER BY id DESC LIMIT 4 (i have posted short example of table and my query)
My table looks like where id is auto increment i only save user_id i only want to take one user_id only once which is lastest entry in database ignore other.
Table
---------------------
id | user_id |
---------------------
13 | 25 |
12 | 36 |
11 | 25 |
10 | 42 |
9 | 95 |
8 | 25 |
7 | 95 |
---------------------
so on
I have tried this
SELECT * FROM `table` GROUP BY user_id ORDER BY `id` DESC LIMIT 4
I want it to output 25,36,42,95 i have also tried many experiments but nothing seems to be working.
Do i need timestamp or something to make it in group? or what query will work?

You are doing a partial GROUP BY which does not work the way you expect. Here is a query which produces the desired results:
SELECT MAX(id) AS MAXID, user_id
FROM `table`
GROUP BY user_id
ORDER BY MAXID DESC
LIMIT 4
The behavior is explained here:
MySQL extends the use of GROUP BY so that the select list can refer to
nonaggregated columns not named in the GROUP BY clause. [...] You can
use this feature to get better performance by avoiding unnecessary
column sorting and grouping. However, this is useful primarily when
all values in each nonaggregated column not named in the GROUP BY are
the same for each group. The server is free to choose any value from
each group, so unless they are the same, the values chosen are
indeterminate. Furthermore, the selection of values from each group
cannot be influenced by adding an ORDER BY clause. Sorting of the
result set occurs after values have been chosen, and ORDER BY does not
affect which values within each group the server chooses.

In your example you need to get result like 25,36,42,95, but sort by ID field.
If you will sort by it you will get different result.
You get a grouping in your query so you cannot use columns that not chosen in query (id is ommited there)
If you still need to order by id, i think that you need to add order by MAX('id') or MIN('id')
In your case i`ll make next query:
SELECT user_id FROM `table` GROUP BY user_id ORDER BY MAX(`id`) DESC LIMIT 4

Try this
SELECT MAX(id) as countid , `user_id` from `table`
GROUP BY `user_id`
ORDER BY countid DESC
LIMIT 20

In stead of grouping, you can use distinct, like below sql query.
SELECT distinct(user_id) FROM `table` ORDER BY `id` DESC LIMIT 4

SELECT * FROM (
SELECT 13 id, 25 UserID
UNION ALL
SELECT 12 id, 36 UserID
UNION ALL
SELECT 11 id, 25 UserID
UNION ALL
SELECT 10 id, 42 UserID
UNION ALL
SELECT 09 id, 95 UserID
UNION ALL
SELECT 08 id, 25 UserID
UNION ALL
SELECT 07 id, 95 UserID
) a
GROUP BY userid ORDER BY id DESC LIMIT 4

Related

Select a table values ordered by two field [duplicate]

How can I sort by multiple columns in SQL and in different directions. column1 would be sorted descending, and column2 ascending.
ORDER BY column1 DESC, column2
This sorts everything by column1 (descending) first, and then by column2 (ascending, which is the default) whenever the column1 fields for two or more rows are equal.
The other answers lack a concrete example, so here it goes:
Given the following People table:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Thomas | More | 1478
Thomas | Jefferson | 1826
If you execute the query below:
SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC
The result set will look like this:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | More | 1478
Thomas | Jefferson | 1826
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC
Multiple column ordering depends on both column's corresponding values:
Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.
Now I perform Order By in these two columns by executing below command:
Now again I insert new values in these two columns, where Alphabet value in ASC order:
and the columns in Example table look like this.
Now again perform the same operation:
You can see the values in the first column are in desc order but second column is not in ASC order.
You can use multiple ordering on multiple condition,
ORDER BY
(CASE
WHEN #AlphabetBy = 2 THEN [Drug Name]
END) ASC,
CASE
WHEN #TopBy = 1 THEN [Rx Count]
WHEN #TopBy = 2 THEN [Cost]
WHEN #TopBy = 3 THEN [Revenue]
END DESC
SELECT id,
first_name,
last_name,
salary
FROM employee
ORDER BY salary DESC, last_name;
If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY. This clause comes at the end of your SQL query.
After the ORDER BY keyword, add the name of the column by which you’d like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name). You can modify the sorting order (ascending or descending) separately for each column. If you want to use ascending (low to high) order, you can use the ASC keyword; this keyword is optional, though, as that is the default order when none is specified. If you want to use descending order, put the DESC keyword after the appropriate column (in the example, we used descending order for the salary column).
SELECT * FROM EMP ORDER BY DEPTNO ASC, JOB DESC;
TRY
'select * FROM users ORDER BY id DESC, name ASC, age DESC
You can also sort or order by the Number of Characters in each Column you wish to sort by. Shown below is a sample which sorts by the first three characters of the First Name and by the last two characters in the name of the town.
SELECT *
FROM table_name
ORDER BY LEFT(FirstName, 3) ASC, LEFT(Town, 2);

Select records from one table and sort the result using a column from another table

I'm working on payroll system for the CRM located at my work and I'm trying to save having to store redundant data which over a period of years will stack up.
I tried to relate it to "how to get value from mysql table ordered by another table?" but had no luck.
I have a Users table
===========================================
# id | username | first_name | last_name #
===========================================
# 1 | joe | Joe | Blow #
===========================================
I also have a Timesheets table which stores the data of each individual session which for the sake of keeping short I have condensed a little in this question and obviously misses the full date/time in start and finish.
============================================
# id | username | start | finish #
============================================
# 1 | joe | 00:00 | 23:59 #
============================================
What I want to achieve is to order the results from the Timesheets table by the last_name column in the Users table with just the username that is derived the Timesheets table.
What I am trying to attempt here:
SELECT * FROM `Timesheets` WHERE `start` >= '{$monday}' AND `finish` <= '{$sunday}' ORDER BY (`Users`.`last_name` WHERE `username` = `Timesheets`.`username`) ASC
MySQL is clearly not my niche, what query would provide the desired result?
You'd have to use a JOIN and then ORDER BY, like this:
SELECT ts.*
FROM timesheets ts
JOIN users
ON ts.username = users.username
ORDER BY users.last_name
You may add the WHERE clause as required before the ORDER BY.
Use JOIN:
SELECT *
FROM Timesheets T
JOIN Users U ON T.username = U.username
WHERE T.start >= '{$monday}' AND `finish` <= '{$sunday}'
ORDER BY U.last_name ASC
use join for this:
SELECT t.*
FROM timesheets t
JOIN users
ON t.username = users.username WHERE t.start >= '{$monday}' AND t.finish <= '{$sunday}'
ORDER BY users.last_name

PHP SQL Return the field with highest count

I need a query which returns the site which contains the highest count.
See a sample table below:
fields:
id | site
1 | site1
2 | site2
3 | site3
4 | site3
In this case above it should return site3.
How can I do this?
SQL Server (SQL Fiddle):
SELECT TOP 1 site
FROM MyTable
GROUP BY site
ORDER BY COUNT(*) DESC
OR MySQL (SQL Fiddle):
SELECT site
FROM MyTable
GROUP BY site
ORDER BY COUNT(*) DESC
LIMIT 1
select site, count(id) from table group by site order by count(id) desc limit 1
Should work
Try this :
SELECT site,
COUNT(site) TotalCount
FROM table_name
GROUP BY site
ORDER BY count(id) DESC LIMIT 1
This one should work
select max(C), S from (select count(id) C ,site S from table group by site) tab
simple count and group your query and order by the count column
SELECT
COUNT(id) as amount,
site
FROM sitetable
GROUP BY site
ORDER BY amount DESC
LIMIT 1
if you want field site as result here's the query:
SELECT COUNT(site), site FROM tab GROUP BY site DESC LIMIT 1
SELECT MAX(id) AS id, site FROM demo
It's return
id site
4 site3

How to check the greatest number in table in SQL using PHP

I was just wondering that, how to get the greatest number in the table.
I mean i have a table called: hits; in that their are 2 columns:
1. id
2. hit
and their are many ids in the table and all have more than 10 hits, now what i want to do is to get the greatest id of the greatest hit
PS: See below:
id | hit
---|----
1 | 10
2 | 15
3 | 45
4 | 9
yes you can use MAX function to use like below
Select Id,Max(hit) from yourtableName group by id having hit=Max(hit)
Select Id,
Max(Hit)
from tableName
group by id
having Max(hit)=(Select Max(Hit) from TableName)
SQL FIDDLE Demo
Wouldn't it be faster to do this:
SELECT * FROM table WHERE 1 ORDER BY hit DESC, id DESC LIMIT 1
Rather than using MAX, Especially if you have a larger table
http://www.witti.ws/blog/2011/04/06/mysqls-max-slow-5-years-later

MySQL use generated column in select query

I have a MySQL query that runs a brief operation (totalling the counts in a select statement) and I want to use the result to do a math operation, but I'm getting an error.
Table:
id | group | count |
-----------------------------
1 1 3
2 1 2
Query:
select id, count,
(select sum(count) from table group by group) as total,
count/total as percent
from table
The error is because there is no real "total" column in the table. How can I make the query work?
You can save total as a variable, then use that in the division calculation.
SELECT
`id`, `count`,
#total:=(SELECT sum(`count`) FROM `table` GROUP BY `group`) AS `total`,
`count`/#total AS `percent`
FROM `table`
NOTE: GROUP is a reserved word in MySQL. You should enclose it (and all other field/table names) in backticks (`).
You can also do this without introducing a variable:
select id,
count,
(select sum(count) from `table` group by `group`) as total,
(select count/total) as percent
from `table`;
Produces:
+------+-------+-------+---------+
| id | count | total | percent |
+------+-------+-------+---------+
| 1 | 3 | 5 | 0.6000 |
| 2 | 2 | 5 | 0.4000 |
+------+-------+-------+---------+
2 rows in set (0.05 sec)
Your problem is that the inner query needs to generate 1 result per row, not 1 for every group. You want to add a where clause in the inner query saying something like
where inner_table.group = outer_table.group
so that only one result is returned.
group is a reserved word in mysql, as is table, you should use it like:
select id, count, (select sum(count) from `table` group by `group`) as total, count/total as percent from `table`
For more information: MySQL Reserved Words
You'll see there that you can actually use count but I would put all table and column names in quotes anyway.
This question already has an answer for MySql but by mistake if anyone lands here for MSSql as i did, it is as simple as below for MSSql
select id, count,
total = (select sum(count) from table group by group),
count/total as percent
from table

Categories