1
                CREATE TABLE IF NOT EXISTS `$id` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                  `start` varchar(10) NOT NULL,
                  `end` varchar(10) NOT NULL,
                  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                  PRIMARY KEY (`id`)
                ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=45 ;


                INSERT INTO `$id`(`start`, `end`) VALUES ('0','0')

I have been trying to figure out how I can bind these two Mysql(requests(?)) into one with no success. Basically I want it to work so when I create the table it should also add the values 0 and 0 to "start" and "end" rows. But I still want the "Create table if not exists" to be in effect for the INSERT INTO. So if the table exist don't INSERT either.

1 Answers1

-1

You could do that with following single statement:

CREATE TABLE IF NOT EXISTS `$id` (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `start` VARCHAR(10) NOT NULL,
    `end` VARCHAR(10) NOT NULL,
    `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB 
SELECT '0' AS `start`, '0' AS `end`;

You use the CREATE TABLE ... SELECT syntax with selecting not from a table, but constant values and get the autoincrement value and the current_timestamp by default.

as of MySQL 5.5.6 or newer, see following excerpt from the manual, CREATE TABLE ... SELECT:

As of MySQL 5.5.6, handling of CREATE TABLE IF NOT EXISTS ... SELECT statements was changed for the case that the destination table already exists. This change also involves a change in MySQL 5.1 beginning with 5.1.51.

Previously, for CREATE TABLE IF NOT EXISTS ... SELECT, MySQL produced a warning that the table exists, but inserted the rows and wrote the statement to the binary log anyway. By contrast, CREATE TABLE ... SELECT (without IF NOT EXISTS) failed with an error, but MySQL inserted no rows and did not write the statement to the binary log.

MySQL now handles both statements the same way when the destination table exists, in that neither statement inserts rows or is written to the binary log. The difference between them is that MySQL produces a warning when IF NOT EXISTS is present and an error when it is not.

This change means that, for the preceding example, the CREATE TABLE IF NOT EXISTS ... SELECT statement inserts nothing into the destination table as of MySQL 5.5.6.

VMai
  • 10,156
  • 9
  • 25
  • 34