Category Archives: MySQL

Get date in Windows CMD script

Apparently it depends on the Windows installation language, how the date function or %DATE% environment variable is formatted. So here is a very ugly hack to get a julian date (YYYYMMDDHHiiss) in a Windows batch script, independent off system locale settings:

  1. @echo off
  2. FOR /F "usebackq tokens=1-10 delims=+|NOW():- " %%a IN (`mysql -e "SELECT NOW();" -u root -ptest`) DO set datetime=%%a%%b%%c%%d%%e%%f
  3. echo %datetime%

Notice that this requires MySQL. If you do not like to use your MySQL root code, you can create a new user with absolutely no rights granted.

But again, this solution is stupid, I hope you will never need it or use it. I just thought I would share, since it was driving my co-worker crazy, and we ended up using it to name a MySQL dump.

Posted in Batch, MySQL | Tagged , , , , | 2 Comments

Select count from multiple tables

Sometimes a parent table have more than one table with multiple references to a field in the parent table. Then the question is how to count references from more than one table in a single query. I have found 5 different ways to achieve this result, and therefore I have run a few tests, to see which was better.

To test this I made this small PHP script, that creates a parent table and child table. Then a loop populates the tables with 1,000 parent rows, approximately 15 children of type 1 and approximately 75 children of type 2. This is done before each query, to make sure that all queries have the same conditions.

Continue reading
Posted in MySQL, PHP | Tagged , , , , , | 2 Comments

Foreign keys and MySQL (errno: 150)

Today I tried to execute the SQL

mysql> ALTER TABLE parent_child ADD FOREIGN KEY (parent_id)
	REFERENCES parent(id) ON DELETE CASCADE;

in MySQL, and got the error

Can't create table 'db.#sql-aa1_1' (errno: 150)

I tried to look up error number 150 on the internet, but found many reasons why error no. 150 could occur; none was my case. Common mistakes that causes this error are:

Continue reading
Posted in MySQL | Tagged , , , | Leave a comment