3

I'm trying to extract data from a MySQL server with PHP. The information has a date field like this YYYYMM (fx. 201108). My question is how would an SQL query look if I wanted to return the first or last half of a specific year? I have tired something like this, however the lessthan seems to be ignored:

SELECT * FROM `poster` WHERE mdr LIKE '2011%' AND mdr < '%06'

I'm afraid google havnt been much help for me.

4
  • 1
    you thread it like a string. so you cant use < Commented Aug 29, 2011 at 12:40
  • what u exact want?? 20 and 11 ?? and what is the datatype of field where u store that date?? Commented Aug 29, 2011 at 12:43
  • If you are storing date as a string, bad for you. You should use the DATETIME data type. Then you can simply use < and > to compare dates. Commented Aug 29, 2011 at 12:43
  • u may b applying STRING function on datetime datatype field Commented Aug 29, 2011 at 12:43

4 Answers 4

1

you can do this, but not with VARCHAR or TEXT:

SELECT * FROM `poster` WHERE mdr < '201106' AND mdr > '201100'
Sign up to request clarification or add additional context in comments.

2 Comments

+1, this will also allow MySQL to keep using an index on field mdr.
In this case you can also do: SELECT * FROM poster WHERE mdr BETWEEN '201101' and '201105'
1

You can only use the % and _ wildcards with the LIKE statement.
This will work, but using any function on a field will kill any opportunity to use indexes, slowing things down.

SELECT * FROM poster WHERE mdr LIKE '2011%' AND right(mdr,2) > '06'

See:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

2 Comments

This worked perfectly, thanks. When i start making my own databases ill sure think about what datatype to use :)
Alright, however this one seems to be easier to use with PHP? with the year as a variable.
1

Try th folowing:

SELECT * FROM `poster` WHERE mdr LIKE '2011%' AND MONTH(STR_TO_DATE(mdr, '%Y%m')) < 06

1 Comment

Indeed, i added the str_to_date
0

TRY ( assuming that datatype is varchar)

SELECT SUBSTRING('YYYYDDMM',FROM 0 FOR 2) AS firstHalf, 
       SUBSTRING('YYYYDDMM',FROM 2 FOR 2) AS SecondHalf
FROM yourTable

References

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.