breq
breq

Reputation: 25506

Mysql "IF" in query

I have few tables

table201202
table201203
table201204
table201205  
...
tableversion

In tableversion I have columns: Version_ID Admin_ID MONTH YEAR

I need to get something like this

Select *
FROM tableversion
LEFT JOIN table(tableversion.month tableversion.year) on
    table(tableversion.month tableversion.year).Version_ID=tableversion.version_id

But in tableversion I've got months without leading 0 so i must check if there is 5 and then change it to 05, if variable is 12 then nothing. How can I do it?

Ok, so now i have something like this

SELECT *, CONCAT('table',IF(tableversion.month < 10, CONCAT('0', tableversion.month ), tableversion.month ),year) as year
FROM tableversion
LEFT JOIN year ON tableversion.version_id=year.version_id WHERE ADMIN_ID=11

#1146 - Table 'database.year' doesn't exist

But it does not work

Upvotes: 1

Views: 1912

Answers (3)

Mahmoud Al-Qudsi
Mahmoud Al-Qudsi

Reputation: 29519

I think an IF statement would likely perform poorly, but I have no data to back that claim.

You can try this alternative to an IF statement to achieve the same: SELECT *, LPAD(month, 2, '0') as month2 ....

Upvotes: 1

Jonathan Hall
Jonathan Hall

Reputation: 79556

As seen here, use LPAD:

SELECT LPAD(month,2,'0') ...

Upvotes: 3

Bryan
Bryan

Reputation: 6752

Try this out in the area where you're concerned about comparing the months

IF(tableversion.month < 10, CONCAT('0', tableversion.month), tableversion.month)

Upvotes: 1

Related Questions