I have DB of posts with:
post_id(int(7)) user_id(int(7)) post_txt(text) post_time(varchar(30)) likes_count(int(10))
(the post_time is look like this "5-4-2016 17:41")
I want to order it by "hot posts" e.g. "likes_count/post_time".
How can I do it?
This is how I do it now:
$que_post=mysql_query("select * from user_post order by post_id desc");
PS. I know that this is not how you save likes usually, but I do it for purpose
Edit-Example data:
97||25||Hello world||8-4-2016 14:19||19
The algorithm I want to use is time/likes. I know its bad algorithm, but I just want to understand the basics.
I would like to know if you know good algorithm for that
You should change type of post_time field to DATETIME (read manual).
All your lines have to be converted by some script to format YYYY-MM-DD HH:MM:SS. When you do it, everything will work.
Your problem appears cause of sorting by alphabet as text. For example: 01.01.2016 as text is less than 31.01.1999.
Assuming you can convert the post_time column to use a date type, you want to find the number of seconds between it and now, e.g.
Order By like_count / (unix_timestamp(now()) - unix_timestamp(post_time)) Desc;
If changing the column type isn't an option, you can convert it on-the-fly using the str_to_date function, but that will potentially be quite a slow operation.
Related
I have a page that displays all projects ordered by dates. When you click on a project you are brought to a page project-single.php?id=123 where I have a previous and next button. All of the projects have an id (which is in no sequential order aka not auto_incremented), and a date of creation timestamp (in the form of 2012-07-20 00:36:20) in the projects table in the database. I am trying to think of an efficient way to get the id of the project both before and after the id=123 in terms of date for the prev next buttons. But I cannot think of an easier way than creating an array with the id and date_created and comparing dates; which as you can imagine would get quite taxing on the server as this is a page accessed often. Does anyone have a cleaner solution?
You might consider changing your timestamp to a Unix timestamp instead of a string. Unix timestamps are simple integers, which are easy and efficient for a database to compare.
With a comparison operator, an index on the timestamp, and a LIMIT 1, you should have a very fast SQL statement. Here's some example code:
-- For getting the next project.
SELECT * FROM projects WHERE date_created > :current_project_date ORDER BY date_created ASC LIMIT 1;
-- For getting the previous project.
SELECT * FROM projects WHERE date_created < :current_project_date ORDER BY date_created DESC LIMIT 1;
I'm not familiar with MySQL, so these results may need some tweaking, but that's the gist.
I am creating a mysql db with a php frontend. The data it will use is extracted from another larger db and contains a date/time field which looks like this - 20120301073136 - which records when an event happened.
I understand that this might be a UNIX timestamp? Not sure.
I want to be show this field in the tables in my PHP webpage as a readable date and time -
ie something like 01-Mar-2012 07:31:36 or similar
Should I try and convert it with SQL command or let PHP format it? And, what is the code to do so?
BTW, it is important that I can sort the data (in SQL and in the PHP table) into date order - ie in the order that these events happened.
Thanks in advance for your help - Ive learnt a lot here already
J
You can convert it to a datetime directly in your SQL query. Example:
select cast(20120301073136 as datetime)
You can also order that with no need to convert it since it is a number in the format YYYYMMDDHHmmss
select * from yourTable
order by yourDateTimeField
You should make use of the MYSQL DATE functions. Check the docs before asking simple questions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html.
Also you can sort the dates directly in your query using ORDER BY.
Is there a way to grab the most recent time of day. If your data in the database is formatted like this 07:00AM and 08:00pm and 12:00pm. Sorta like max(). But for the time. In a Mysql query.
Thanks
Eric
It would be best to store it in another format rather than as text. Or at least store it in 24 hour format, then a simple sort would work. You can convert it to 12-hour format when you display the data to the user.
But assuming you can't change your database schema, try this:
SELECT *
FROM your_table
ORDER BY STR_TO_DATE(your_time, '%h:%i%p') DESC
LIMIT 1
Note that this won't be able to use an index to perform the sorting.
You should try STR_TO_DATE() instead if you're using a string. If your times are always formatted as hh:mmAMPM, you can use:
MAX(STR_TO_DATE(YourTimeField,'%h:%i%p'))
This converts your string to a time, without any need to split it up by substring or anything, so MySQL would then see 09:07AM as 09:07:00 and 02:35PM as 14:35:00, and then would easily be able to determine the MAX of it.
Assuming you are dealing with a DATETIME field in your MySQL, you can use this query to get the max time per day:
SELECT DATE(YourDateField), MAX(TIME(YourDateField)) FROM YourTable
GROUP BY DATE(YourDateField)
When you are dealing with a VARCHAR field, you can try a hack like this:
SELECT YourDateField, SUBSTRING(MAX(
CASE WHEN YourTimeField LIKE '%AM%' THEN '0' ELSE '1' END
+ REPLACE(YourTimeField, '12:', '00:')
), 2)
GROUP BY YourDateField
You can just sort.
select time_column from table order by time_column desc limit 1;
$months = array('January', ... , 'December');
$sql='
SELECT *
FROM `residencies`
WHERE `Year` = 2010
ORDER BY array_search($months,`MonthFrom`) `DayFrom`';
Doesn't work (i already feared that), it's supposed that the elements are sorted by first the position of MonthFrom in the array $months, and those who have the same position should be sorted by DayFrom. I know there are other way's to treat dates but for this query i am bound to this date structure, any help is appreciated
$month_arr = array("January","February","March");
$months = implode("', '", $month_arr);
$query="SELECT * FROM residencies WHERE year = 2010 ORDER BY FIELD('MonthFrom', '$months'), `DayFrom`;
$sql='
SELECT *
FROM `residencies`
WHERE `Year` = 2010
ORDER BY DATE_FORMAT(`MonthFrom`,"%M") `DayFrom`';
But this will sort them according to the alphabetical order of the name of the month ? Do you really need that ?
You can also sort them according to MonthFrom and them convert it to text in your php code."
It looks like you're trying to use a PHP function within an SQL statement. If you need to sort by MonthFrom, which is the name of the month, try something like this:
SELECT *
FROM `residencies`
WHERE `Year` = 2010
ORDER BY FIELD(`MonthFrom`, 'January', ..., 'December'), `DayFrom`;
(you can fill in the rest of the months)
I presume from the question that you have a month field in the database which is stored in string format, which would, as other commenters have said, make sorting tricky, hence why you were trying to put the months in order using the array.
Others have come up with valid ways to achieve this given that constraint (I think luckytaxi's answer is probably the best so far), but I would say that if you do have months stored in the database in string format, then you definitely have a poor database design, and if you have the option, you should consider changing it.
MySQL can store full dates using the DATE or DATETIME data types, so if you're storing your days, moths and years separately at the moment as it appears, you should change to storing them together in a single field. You can still query them separately, eg if you just need the month, or in any combination - MySQL has very powerful date handling features (and so does PHP for that matter).
I have a php page which allows a user to sort pieces of information by several factors. A new requirement is to sort by "all items which have been registered in the last 15 days". I store my dates in the MYSQL table as mm/dd/yyyy.
The information is passed and picked up on the same page using the $_GET variable but I am unable for some reason to get the code to work. I have looked on numerous website but am unable to find a solution that works.
Ultimately, the script would work as follows:
select all persons who's KDATE is within 15 days of today's date (e.g., if today is 8/19/2010, everybody who registred from 8/04/2010 and on would appear).
My script so far (which does not work) is:
if (isset($_GET['date'])) {
$query = "SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= KDATE
ORDER BY KDATE ASC";
}
Update 1:
KDATE IS TEXT - i apologize but the KDATE is stored as TEXT
Update 2:
The answer provided by Colin solved my issue. I will look into trying to convert the data into datetime format but am hoping the group can provide realistic benefits of doing so.
Thank you all again
First of all, it's a really bad idea to use VARCHAR instead of DATE if you want a collumn with dates only.
If you want to use a string as a date, you'll need to convert it with STR_TO_DATE() and you might wan't to use those instructions to correctly format your date.
This should do it:
SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= STR_TO_DATE(KDATE, "%c/%d/%Y")
ORDER BY STR_TO_DATE(KDATE, "%c/%d/%Y") ASC
Because kdate is VARCHAR, you need to use STR_TO_DATE to change it to a DATETIME.
You need to fix kdate data that does not fit that pattern (mm/dd/yyyy) before running this:
SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= STR_TO_DATE(KDATE, 'm/%d/%Y')
ORDER BY STR_TO_DATE(KDATE, 'm/%d/%Y') ASC
This means that an index on kdate is useless, because of having to change the data type.
Once it's a DATETIME, you can use DATE_FORMAT to change the format as you like.