I have a MySQL table:
dateStarted varchar(45)
dateEnded varchar(45)
Example:
alt text http://img8.imageshack.us/img8/765/dated.jpg
There is varchar (I don't know why the previous software engineer used this).
Can I search between two dates in MySQL with the varchar type?
Nope. You have to change the format to a proper one.
The previous software engineer used this because of ignorance. You have to correct his mistake.
Don't be afraid of some extra work. Actually it's part of every programmer's job. There is no code in the whole world, which is perfect forever. Constant code improving is called refactoring and take a big part of every software engineer's worktime.
SELECT
*
FROM test1
WHERE STR_TO_DATE(:date, '%d-%m-%Y') BETWEEN
STR_TO_DATE(dateStart,'%d-%m-%Y') AND
STR_TO_DATE(dateEnd,'%d-%m-%Y')
Just tried this on your dataset, and it works AFAICT.
But you should of course heed the advice given by the others here, and try to fix your predecessor's mistakes, if at all possible within time-constraints. This will become an issue at some point, due to the amount of casting going on.
You will need to determine the format that the two fields are in. Are they seconds from UNIX epoch? Are they YYYYMMDD format? Once you've done that, it would be fairly easy to convert it to a date and compare them.
Related
I've hunted around and found plenty of ways to convert a string to a date, but I can't seem to find one for the reverse... so here we go.
I'm trying to build a text string for a query, specifically running through WordPress on MySQL, for the BAW Post Count plugin data. That plugin uses a meta-key which always begins the same (count-views) and is followed by 'day', 'month' and so on, then the date part.
What I want to do is specify which meta-key I'm looking for by building a text string based on the current date:
"_count-views_month-" then the 4-figure year and two-figure month.
For example, this month is October 2013, so it would come out as "_count-views_month-201310"
The problem is that I can't seem to find a way to get the year and month as text, for use in a php script.
I've tried using year(now()),year(date(now())), cast, concat and a variety of other things but none seem to work. I know it must be incredibly easy and I'm just complicating matters or overlooking something obvious, but I can't see what!
So, the question is how I can do that as a "$variable=" statement, please.
Thanks!
You over-thought it:
echo date("Ym"); // outputs "201310"
Full example:
echo '_count-views_month-' . date("Ym");
Or:
printf("_count-views_month-%s", date("Ym"));
Or, in SQL:
SELECT CONCAT("_count-views_month-", DATE_FORMAT(CURRENT_DATE, "%Y%m"))
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the pros and cons of the various date/time field types in MySQL?
In many database, I saw they use TIMESTAMP type to store time value, my question is why don't use INT type to store $date->getTimestamp() value and then we could get time value easier?
Because when you treat a date as a date, and not as a number, you can do neat stuff like adding durations (DATE+1MONTH-1HOUR). TIMESTAMP, DATETIME etc are also optimized for dates, and will do native validation for you.
There can be many reasons, I'd say the most obvious (and straight forward one) is that the databse knows that the value is a TIMESTAMP (so Date/Time related), which is not the case for an INT.
This has several consequences, for example that Mysql is aware of timezones and automatically concerts the TIMESTAMP to UTC. That means the data is much more concrete, because it is clear what the data means. For the INT types you would need to take care of that your own, it would not be relative to the database any longer.
The next big difference is automatic initialization and updating. That means, if the row is inserted or changed, a TIMESTAMP column will get "stamped" with the current time.
There are several other differences then as well between these types, most of the are related to data/time functions. I suggest you dig into:
11.3.1. The DATE, DATETIME, and TIMESTAMP Types
You can do many more things in the database when using a timestamp instead of a plain number. Query by day of week, group by month, determine intervals, etc...
An int is only 4 bytes a datetime is 8 bytes so you'd have less possible values. In particular for php you are getting Unix timestamps which have a min date 1901-12-13, and max of 2038-01-19. This is essentially going back and making the same sort of decisions that lead to the Y2K problem. Assuming you can live with that you should be okay but what about non-Unix based hosts?
Because actual representation of data does not have to be exposed. Why?
flexibility (internal representation of data may change any time and user won't depend on it).
reliability (database may check data for consistency if it knows what the data is)
readability (there's no reason to treat a timestamp as integer, it shows the meaning of a record)
The reason there are different number types (such as timestamp), is to provide data integrity.
Data Integrity makes sure that we don't accidentally put in the number of waffles we had for breakfast :)
If we try to put in an invalid timestamp, MySQL will throw an error and prevent us from putting in bad data.
I have two choices of storing date and time in my database.
Generate the time & date from time function in php and then storing in database into int datatype which is of 4 bytes.
Generate the time & date during insertion in database into datetime datatype which is of 8 bytes.
My question is which type will make my SQL queries faster if I use date&time column for sorting.
I always hate it building queries on a DB that contains human unreadable date and time values in int format.
Maybe the query will be a nano second faster if you use int but is it really worth it? I say no!
Use a TIMESTAMP datatype. It's stored as a number, but returned formatted. So it's faster for sorting, and more human-readable.
You are better off using the native format of the database to store date times.
I can see almost no occasion where you would want to use another binary format for this purposes. That would make that component of the database essentially inoperable for other access methods.
As for human readability, you can solve that issue by having views access the tables (in other databases you can define a table with computed columns) that provide the dates in human readable format. Also, tools that know the database should produce the output in human readable format.
Unless you have a very large database or are in a very tightly constrained environment, then don't worry about storage. You are probably not thinking about the extra bits that are stored when you allow NULLs for a column, or the extra padding that might go between fields when they are no aligned on hardware word boundaries, or the empty space on data pages because the records don't align on page boundaries.
If space is such an important consideration, then you might want to develop your own date/time format to see if you can get it down to 2 or 3 bytes.
I am coding a social network and I need a way to list the most used trends, All statuses are stored in a content field, so what it is exactly that I need to do is match hashtag mentions such as: #trend1 #trend2 #anothertrend
And sort by them, Is there a way I can do this with MySQL? Or would I have to do this only with PHP?
Thanks in advance
The maths behind trends are somewhat complex; machine learning may be a bit over the top, but you probably need to work through some examples.
If you go with #deadtrunk's sample code, you would miss trends that have fired up in the last half hour; if you go with #eggyal's example, you miss trends that have been going strong all day, but calmed down in the last half hour.
The classic solution to this problem is to use a derivative function (http://en.wikipedia.org/wiki/Derivative); it's worth building a sample database and experimenting with this, and making your solution flexible enough to change this over time.
Whilst you want to build something simple, your users will be used to trends, and will assume it's broken if it doesn't work the way they expect.
You should probably extract the hash tags using PHP code, and then store them in your database separately from the content of the post. This way you'll be able to query them directly, rather then parsing the content every time you sort.
I think it is better to store tags in dedicated table and then perform queries on it.
So if you have a following table layout
trend | date
You'll be able to get trends using following query:
SELECT COUNT(*), trend FROM `trends` WHERE `date` = '2012-05-10' GROUP BY trend
18 test2
7 test3
Create a table that associates hashtags with statuses.
Select all status updates from some recent period - say, the last half hour - joined with the hashtag association table and group by hashtag.
The count in each group is an indication of "trend".
I have been given the task to combine 2 mysql fields into one and then make it so that the new field can be searched. The 2 fields I had to combine in my database where previous year registered and current years registered. The format both these fields are in are dd/mm/yyyy. I have combined these fields into a field called Years Registered whih is still in the same format dd/mm/yyyy but has the years registered seperated by a comma(,). I am wondering how I would go about performing a couple different kinds of querys on this column. The mysql queries I have to perform are: Show All() , Show All between dates: mm/yyyy and mm/yyyy , Before: mm/yyyy , After: mm/yyyy
Any help would be greatly appreciated.
Thanks for your time.
I don't like it but if you need you can use the next solution:
extract date using start_date = STR_TO_DATE(SUBSTRING(your_new_field, 1, 10))
and end_date=STR_TO_DATE(SUBSTRING(your_new_field, 12, 10))
Do not do this!
I do not know how it is exactly possible (some SQL Stringoperations and Datefunctions in a storedprocedurem i presume), but it will surely kill performance of your database.
use a relation for this.
This is:
way faster
more expandable (eg. for three dates..)
easier to code
much better understandable
more portable to other databases
If you have problems with existing platforms you have to support, use a code base where both alternatives are supported. This is still easier and better to maintain than to use a comma-separated list
Your database would be breaking 'First Normalized Form (1NF)' and would be highly ineffecient.
In order to search for a selected date, you would either have to query all rows in the table, or use LIKE which is also very sluggish.
Whoever is asking you to do this should read this article on database normalization.
What is wrong with using two DATE, or DATETIME fields and the formatting them outside of MySQL?