How to order DATETIME rows with [] in MySQL - php

I have a mysql "users" table like this example:
id | user | created
100 | user001 | [27-01-2016 04:30 PM]
101 | user005 | [19-05-2017 09:28 AM]
102 | user019 | [09-10-2015 03:29 PM]
103 | user029 | [18-11-2017 05:40 PM]
And I want to get this table in descending order by created row like this:
id | user | created
103 | user029 | [18-11-2017 05:40 PM]
101 | user005 | [19-05-2017 09:28 AM]
100 | user001 | [27-01-2016 04:30 PM]
102 | user019 | [09-10-2015 03:29 PM]
I tried with DATE_FORMAT:
SELECT id,user,DATE_FORMAT(created,"%d %m %Y") AS created FROM users ORDER by created desc
But it shows nothing, how can I get it?
I'd like some help.

This works:
SELECT `id`, `user`, DATE_FORMAT(STR_TO_DATE(MID(`created`, 2, 19), '%d-%m-%Y %h:%i %p'), '%d-%m-%Y %h:%i %p')
AS `created:` FROM `users` ORDER BY STR_TO_DATE(`created:`,'%d-%m-%Y %h:%i %p') DESC
Here is a working SQL Fiddle.
Explanation:
The MID() MySQL function returns the middle part of a string, so we easily stripped out the []. After that, the STR_TO_DATE() function parses the returned string into DATETIME format (the %p is for AM/PM). The returning value is not properly formatted, at least not in the way you would wish to have it. So we then use DATE_FORMAT() to format the output. In the end, we use STR_TO_DATE() once again for the ordering since created: is returned as string.
I also changed your created output column to created: since it will not work if they are all the same name.

Your created date format isn't correct, you should alter the table and change the field from varchar/char(string) to timestamp type. I have already tried converting your string dates with 'STR_TO_DATE()' but it returns null because the format doesn't match either timestamp, date or time formats. Its always best practice to store dates/datetime as either date or timestamp data types. You can always apply formatting functions later in query to output dates to any desired format.

Related

Complex Queries range dates

mySQL dateTime range Query Issue
how get count of proceser in 2017 by same date like 2017-08-07
date | name
-----------------------
2017-08-31 | amr
-----------------------
2017-08-05 | ahmed
----------------- -----
2018-08-08 | moh
how get 2017-01-01 BETWEEN 2017-12-31
------------------------
count | date
-----------------------
2 | 2017
-----------------------
1 | 2018
SELECT count(*)
FROM item WHERE
date IN
( SELECT date
FROM item WHERE
(BETWEEN '2017-03-15' AND '2017-09-31'))
I couldn't find a duplicate for you, but I am sure there is one somewhere.
If you use GROUP BY and the DATE_FORMAT() function, you can COUNT() the occurrences in each group.
SELECT COUNT(*),DATE_FORMAT(`date`,'%Y') FROM `item` GROUP BY DATE_FORMAT(`date`,'%Y');
You can include a WHERE clause before GROUP BY if you need to omit certain ranges of time.
1, date is a reserved MySQL word. It would be best to name your column something else, but you can use it if you also specify the table name like table.date
2, there is no need for a sub-query. MySQL can do this in one query
SELECT count(`table.name`) as NUMBER, YEAR(`table.date`) as YR FROM item WHERE DATE(`table.date`) BETWEEN '2017-01-01' AND '2017-12-31'
BETWEEN is kind of a "ternary" operator, of the form x BETWEEN y AND z
You want:
`date` BETWEEN '2017-03-15' AND '2017-09-31'

MySQL - saving date and time as DATETIME vs as saving date and time as String

I need to store a deadline, that consists of a date and a time (e.g 2016-05-02 19:02). I am currently using a field that has DATETIME as datatype but the problem is that its automatically saving it as 2016-05-02 19:02:00.
as a solution i was thinking to save the date in a String field.
So i am wondering if i should do that ? any performance advantages/disadvantages ?
Don't fight the database. Use the builtin types unless you really need something that they can't offer(I'd say it's unlikely, though). (And by this I mean that you should use TIME, DATE or similar for times and dates. Then you can do calculations without having to convert values, etc)
If you don't need the seconds then just keep them 00 all the time.
Whether you use DATETIME, DATE & TIME or perhaps TIMESTAMP is up to you, how you use the data. Choose the alternative that makes most sense in your current situation.
As mentioned in the other answer, you should always use built-in data types whenever possible.
In your case, stick with DATETIME and then convert it to whatever format you need in the query using the DATE_FORMAT function, like so:
mysql> SELECT * FROM `mytable`;
+----+---------------------+
| id | mydatetime |
+----+---------------------+
| 1 | 2016-06-06 14:12:00 |
+----+---------------------+
1 row in set (0.00 sec)
mysql> SELECT DATE_FORMAT(`mydatetime`,'%b %d %Y %h:%i %p') AS `mydatetime` FROM `mytable`;
+----------------------+
| mydatetime |
+----------------------+
| Jun 06 2016 02:12 PM |
+----------------------+
1 row in set (0.00 sec)
Reference:
http://www.w3schools.com/sql/func_date_format.asp

Find out which months have data logged in MYSQL database?

In my database I have the date of each customer order stored in the format 02 Mar 2015
I have data from March and April and I want a query that will return just those 2 months. Once I have data for May it will return the three months etc.
The SQL syntax which I am trying to use is:
SELECT DISTINCT MONTH(DATE_FORMAT(date,'%d %b %y')) FROM orders
However this returns 0 rows. I presume this is an issue with date format.
EDIT:
Sample data from table:
id | date | time | order_id | item | quantity
1 | 02 Mar 2015 | 14:22 | 1029 | clasico | 9
1 | 05 Apr 2015 | 13:58 | 1029 | hindu | 10
try
SELECT DISTINCT MONTH(`order_date`) FROM `orders`
where order_date is the date field in orders
Note: The answer assumes the date column is a varchar rather than a datetime datatype.
The DATE_FORMAT() function is used to display date/time data in different formats. Note: This assumes the data is a datetime data type.
The STR_TO_DATE() returns a datetime value by taking a string and a specific format string as arguments. See the code below in action in the SQL Fiddle demo.
select DISTINCT MONTH(STR_TO_DATE(date, '%d %b %y')) from orders

Date format in SQL query

i have table:
Birthday
id | name | date
1 | aaa | 1990-03-02
2 | bbb | 1990-03-12
3 | ccc | 1990-03-25
4 | ddd | 1990-04-25
5 | eee | 1990-04-23
6 | fff | 1990-04-26
7 | ggg | 1990-04-12
How is the best way to SELECT all names where date is 1990-04-xx?
SELECT name FROM table WHERE date LIKE '1990-04%'
Some other answers here are assuming you're storing the date in a datefield, but I assumed by the way it was laid out in your question that it was just a string. Going on that assumption, I knew that using the LIKE operator would let me use a wildcard (the % sign) to search for anything with that year and month. That said, this query will match anything that starts with 1990-04 so there is a possibility with malformed data that you could get some incorrect data (e.g. a date is entered into the database like '1990-041-12')
If it's a DATE value I'd suggest checking if it's between the beginning and the end of the month. If you chop up the date using DATE_FORMAT or some other function you'll lose any chance of optimization:
SELECT name FROM myTable WHERE `date` BETWEEN '1990-04-01' AND '1990-04-30'
If it's a DATETIME value, do this instead to account for values like 4/30/1990 at 9PM:
SELECT name FROM myTable WHERE `date` >= '1990-04-01' AND `date` < '1990-05-01'
If date is a DATE or DATETIME or TIMESTAMP column and you want an index to have chances to be used:
SELECT name
FROM tableX
WHERE date >= '1990-04-01'
AND date < '1990-05-01' ;
An index on (date) would be good. Even better, an index on (date, name).

MySQL: How to do daily reports?

Assume I have a log of something. Each record has a timestamp (MySQL data type TIMESTAMP) in the format date('Y-m-d H:i:s') (from PHP). I need to produce a report that looks like this:
===========================================
| Date | Total Sales |
===========================================
| Thursday, Dec 1, 2011 | 100 |
-------------------------------------------
| Friday, Dec 2, 2011 | 200 |
-------------------------------------------
| Saturday, Dec 3, 2011 | 150 |
-------------------------------------------
... and so on ...
I assume I have to dynamically build the SQL from PHP, which is OK. I'm just not sure what the SQL would look like. Ideas?
How to count the number of records per day
This is what I originally thought you wanted. I'm leaving it here because it might be useful to other people.
You have a bunch of timestamps. You want to group them by individual days and get the number of records per day.
Assuming your timestamp field is named ts, you can do something like this:
SELECT COUNT(*), DAY(ts), MONTH(ts), YEAR(ts) FROM tableName
GROUP BY YEAR(ts), MONTH(ts), DAY(ts);
How to generate daily reports for individual people
Ok this is what you really wanted. Let's draw a sample table with some records:
ts person sales
2011-12-01 10:00:00 John 10
2011-12-01 10:30:00 Mary 25
2011-12-01 11:00:00 John 20
2011-12-02 14:00:00 John 40
To get the daily totals for a particular person, you would do:
SELECT SUM(sales), DAY(ts), MONTH(ts), YEAR(ts) FROM tableName
WHERE person='John'
GROUP BY YEAR(ts), MONTH(ts), DAY(ts);
This is selecting records where person is John, grouped by unique days, and summing the sales value for those records. If you want reports for every person combined, just remove the WHERE clause.
Final note
You can simplify your SQL a little bit if you use the DATE type instead of the DATETIME type. I'm selecting and grouping by the day, month and year which I need to get using three separate functions. If you're using the DATE type, calling these functions would be unnecessary and I could just select and group by ts directly. It's up to you how you want to represent your data.

Categories