Group SQL rows by column value without flattening [duplicate] - php

Is it possible to sort in MySQL by "order by" using a predefined set of column values (ID) like order by (ID=1,5,4,3) so I would get records 1, 5, 4, 3 in that order out?
UPDATE: Why I need this...
I want my records to change sort randomly every 5 minutes. I have a cron task to update the table to put different, random sort order in it.
There is just one problem! PAGINATION.
I will have visitors who come to my page, and I will give them the first 20 results. They will wait 6 minutes, go to page 2 and have the wrong results as the sort order has already changed.
So I thought that if I put all the IDs into a session on page 2, we get the correct records even if the sorting had already changed.
Is there any other better way to do this?

You can use ORDER BY and FIELD function.
See http://lists.mysql.com/mysql/209784
SELECT * FROM table ORDER BY FIELD(ID,1,5,4,3)
It uses Field() function, Which "Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found" according to the documentation. So actually you sort the result set by the return value of this function which is the index of the field value in the given set.

You should be able to use CASE for this:
ORDER BY CASE id
WHEN 1 THEN 1
WHEN 5 THEN 2
WHEN 4 THEN 3
WHEN 3 THEN 4
ELSE 5
END

On the official documentation for mysql about ORDER BY, someone has posted that you can use FIELD for this matter, like this:
SELECT * FROM table ORDER BY FIELD(id,1,5,4,3)
This is untested code that in theory should work.

SELECT * FROM table ORDER BY id='8' DESC, id='5' DESC, id='4' DESC, id='3' DESC
If I had 10 registries for example, this way the ID 1, 5, 4 and 3 will appears first, the others registries will appears next.
Normal exibition
1
2
3
4
5
6
7
8
9
10
With this way
8
5
4
3
1
2
6
7
9
10

There's another way to solve this. Add a separate table, something like this:
CREATE TABLE `new_order` (
`my_order` BIGINT(20) UNSIGNED NOT NULL,
`my_number` BIGINT(20) NOT NULL,
PRIMARY KEY (`my_order`),
UNIQUE KEY `my_number` (`my_number`)
) ENGINE=INNODB;
This table will now be used to define your own order mechanism.
Add your values in there:
my_order | my_number
---------+----------
1 | 1
2 | 5
3 | 4
4 | 3
...and then modify your SQL statement while joining this new table.
SELECT *
FROM your_table AS T1
INNER JOIN new_order AS T2 on T1.id = T2.my_number
WHERE ....whatever...
ORDER BY T2.my_order;
This solution is slightly more complex than other solutions, but using this you don't have to change your SELECT-statement whenever your order criteriums change - just change the data in the order table.

If you need to order a single id first in the result, use the id.
select id,name
from products
order by case when id=5 then -1 else id end
If you need to start with a sequence of multiple ids, specify a collection, similar to what you would use with an IN statement.
select id,name
from products
order by case when id in (30,20,10) then -1 else id end,id

If you want to order a single id last in the result, use the order by the case. (Eg: you want "other" option in last and all city list show in alphabetical order.)
select id,city
from city
order by case
when id = 2 then city else -1
end, city ASC
If i had 5 city for example, i want to show the city in alphabetical order with "other" option display last in the dropdown then we can use this query.
see example other are showing in my table at second id(id:2) so i am using "when id = 2" in above query.
record in DB table:
Bangalore - id:1
Other - id:2
Mumbai - id:3
Pune - id:4
Ambala - id:5
my output:
Ambala
Bangalore
Mumbai
Pune
Other

SELECT * FROM TABLE ORDER BY (columnname,1,2) ASC OR DESC

Related

How to fetch value according to the proper order using PHP and Mysql

I need one help.I need to fetch value according to the one certain order using PHP and Mysql.I am explaining my table below.
db_subcategory:
id cat_id name order
1 10 happy hour 1
2 10 wine 3
3 10 water 2
4 11 pizza 1
5 10 beer 2
Here i need query in Mysql to fetch all name whose cat_id=10 according to the order.It should come as per order1,2,3... if for order value 2 there are two set of name,in this case the name will come alphabetically.Please help me.
SELECT name
FROM db_subcategory
WHERE cat_id = 10
ORDER BY `order`, name
EDIT: It might also needed to add backticks for order because it is a keyword.
Demo.
Order by with two columns will do.
select * from db_subcategory where cat_id = 10 order by order, name

show matching mysql table results only once?

hi I'm looking for a way to only show a matching set of mysql results only once. can anyone tell me how to do this?
here's an example of what i'm trying to achieve:
id | profile_id | viewed_profile_id | date_viewed
1 4 7 00:00:00
2 5 6 00:00:00
1 4 7 00:00:00
so if profile_id and viewed_profile_id match then to only show one result for those matching columns rather than twice or three times or however many times it appears in the database?
Use the DISTINCT keyword:
SELECT DISTINCT id, profile_id, viewed_profile_id, date_viewed
FROM myTable
This will show only one row for each unique combination of the columns selected.
Or, reading into your question a lot (since you only want to match profile_id and viewed_profile_id), if you want to show the latest date viewed for each viewer, you can use GROUP BY and select the MAX date viewed. I am also assuming there is data in date_viewed and it is sortable:
SELECT profile_id, viewed_profile_id, MAX(date_viewed)
FROM myTable
GROUP BY profile_id, viewed_profile_id
DISTINCT helps to eliminate duplicates. If a query returns a result that contains duplicate rows, you can remove duplicates to produce a result set in which every row is unique. To do this, include the keyword DISTINCT after SELECT and before the output column list
http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
SELECT DISTINCT(` profile_id`),`viewed_profile_id`,`id`,`date_viewed` FROM `tableName` GROUP BY `viewed_profile_id`
try this:
$query = "SELECT * FROM TABLENAME WHERE profile_id = '$PROFILEIDVALUE' AND viewed_profile_id = '$VIEWEDIDVALUE' LIMIT 0, 1"
Depending upon the ORDER you want use can use ORDER BY id DESC/ASC
I hope this would be useful

MySQL Query line, 3 highest values?

I am creating a blog and I have decided to order my blog by the ID, this is because I want to display 3 on the homepage and all of them in the blog. Anyhow thats not my problem straight to the point I need help with my MySQL Query.
Say for example I have the following ID's in the Database: 1 2 3 4 5 6 7 8 9 10.
I only want to show 3, the newest 3 so 8, 9 then 10. I dont know how I'd Query this could I please ask for a Query line for my MySQL please?
I know this is a stupid question I have found example of what I mean but Its talking about adding 2 numbers together? I only need the one number placed in order.
Anyhow, thanks guys!
You can sort by the ID, descending. This will place the post with the highest ID at the start of the result set. You can then use LIMIT to only return 3 results (i.e. the latest 3).
SELECT `post_id` FROM `tblName` ORDER BY `post_id` DESC LIMIT 3
Try this:
SELECT *
FROM [TableName]
ORDER BY ID DESC
LIMIT 3
SELECT * FROM table WHERE true ORDER BY id DESC LIMIT 3

how to get last inserted date in php MYSQL

I have two tables, and I want to get the last enterd date.
The first table is seeker:
seeker_nic-----username
111-------------ali
222-------------umer
333-------------raza
The second one is requestblood:
id-------seeker_nic-----requireddate
1------- 111 ----------2012/10/9
2 ------- 222-----------2012/5/8
3 ------ 111-----------2012/12/12
4 ------- 111-----------2012/11/12
5---------111-----------2012/09/09
6 ------- 222-----------2012/7/9
7 ------- 333 ----------2012/4/4
Now, I want to list the users one time with their last inserted date like..
s.no---- username----- requireddate
1------- ali---------- 2012/09/09
2------- umer--------- 2012/7/9
3------- raza--------- 2012/4/4
I am using this query, but it shows maximum date not the latest one.
SELECT seeker.username, MAX(bloodrequest.requireddate) AS requireddate, COUNT(bloodrequest.requireddate) AS total
FROM seeker
JOIN bloodrequest
ON seeker.seeker_nic = bloodrequest.seeker_nic
GROUP BY seeker.username
This shows the maximum date, and it shows total dates. For example, 111 has total "4", but I don't know how to show the last inserted date... I am new in PHP, please help me. :(
Thanks in advance!
Very simple but you will need to use subselect - acquire row with last id (this will work only if you have correct indexing - i suppose you have).
Example:
SELECT seeker_nic, username,
(SELECT `requiredate` FROM `requestblood` WHERE `seeker_nic`=`seeker`.`seeker_nic` ORDER BY `id` DESC LIMIT 1) as `last_requiredate`
FROM `seeker`

php / mysql - how to get rankings of users?

for example i have a table like this :
name rating
matei 124
andrei 20
serj 25
john 190
mike 96
andy 245
tom 73
i need to output something like this(order by rating):
john's position is 2; or, tom's position is 5; (i don't need to get all result , just one )
How can I achieve this?
Thanks in advance
Generally order of rows in a query result is not guaranteed by MySQL unless ordering is explicitly specified with ORDER BY clause. If you have some separate ordering column, you may use query like the following:
SELECT count(1) as position
FROM table
WHERE order_column <= {john's order_column value};
If you don't have ordering column, I'd recommend you to define first, what does "john's position" and "tom's position" mean.
UPDATE:
AFAIU, you want to get position in list sorted by rating (sorry, I initially did not get it). So, rating would be your order_column. In this case, you should decide, how do you calculate position, if two guys have equal rating (who's position is higher?).
So, the query may look in the following way:
SELECT count(1) as position
FROM table
WHERE
rating > (SELECT rating FROM table WHERE id={user's ID});
SELECT COUNT(*) + 1
FROM users
WHERE (rating, name) <
(
SELECT rating, name
FROM users
WHERE name = 'john'
)
Note that if you will have duplicates on both name and rating, this query will assign the same rating to both of them.
Tables are more formally known as relations in database literature - they are not guaranteed to be ordered (they are sets of "tuples"), so your question doesn't make sense. If you need to rely on an order/position, you need to define an additional column (like an auto-incrementing ID column) to capture and store that info.
Is this any help > http://craftycodeblog.com/2010/09/13/rownum-simulation-with-mysql/ ?
Would offset not work like so?
SELECT * FROM Table ORDER BY rating DESC LIMIT 1,6
This would return 1 row that has been off setted by 6 rows ? or am I mistaken, the syntax would be
SELECT * FROM Table ORDER BY rating DESC LIMIT 1 , {{POS}}

Categories