Getting 1005 constraint error on create table












0















I am making a script that reading some php files creates a SQL file. I have almost finished, but I am getting a MySQL error that I can't figure it out :(



This is the SQL code:



CREATE TABLE `tag` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Id único de cada tag',
`name` VARCHAR(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Nombre de la tag',
`id_user` INT(11) NOT NULL COMMENT 'Id del usuario',
`created_at` DATETIME NOT NULL COMMENT 'Fecha de creación del registro',
`updated_at` DATETIME NULL COMMENT 'Fecha de última modificación del registro',
PRIMARY KEY (`id`),
KEY `fk_tag_user_idx` (`id_user`),
CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Id único de un usuario',
`user` VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Nombre de usuario',
`pass` VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Contraseña del usuario',
`num_photos` INT(11) NOT NULL DEFAULT '0' COMMENT 'Número de fotos de un usuario',
`score` FLOAT NOT NULL DEFAULT '0' COMMENT 'Puntuación del usuario',
`active` TINYINT(1) NOT NULL DEFAULT '1' COMMENT 'Usuario activo 1 o no 0',
`last_login` DATETIME NOT NULL COMMENT 'Fecha de la última vez que inició sesión',
`notes` TEXT NOT NULL DEFAULT '' COMMENT 'Notas sobre el usuario',
`created_at` DATETIME NOT NULL COMMENT 'Fecha de creación del registro',
`updated_at` DATETIME NULL COMMENT 'Fecha de última modificación del registro',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


There are more tables, but these are the first two and it already crashes with:



#1005: Can't create table `tag` (Error: 150)


The script starts with SET FOREIGN_KEY_CHECKS = 0; and ends with SET FOREIGN_KEY_CHECKS = 1;



Any help would be appreciated, thanks!!










share|improve this question


















  • 3





    Create the user table first. It has to exist so the other table can refer to it

    – juergen d
    Nov 21 '18 at 10:53
















0















I am making a script that reading some php files creates a SQL file. I have almost finished, but I am getting a MySQL error that I can't figure it out :(



This is the SQL code:



CREATE TABLE `tag` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Id único de cada tag',
`name` VARCHAR(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Nombre de la tag',
`id_user` INT(11) NOT NULL COMMENT 'Id del usuario',
`created_at` DATETIME NOT NULL COMMENT 'Fecha de creación del registro',
`updated_at` DATETIME NULL COMMENT 'Fecha de última modificación del registro',
PRIMARY KEY (`id`),
KEY `fk_tag_user_idx` (`id_user`),
CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Id único de un usuario',
`user` VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Nombre de usuario',
`pass` VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Contraseña del usuario',
`num_photos` INT(11) NOT NULL DEFAULT '0' COMMENT 'Número de fotos de un usuario',
`score` FLOAT NOT NULL DEFAULT '0' COMMENT 'Puntuación del usuario',
`active` TINYINT(1) NOT NULL DEFAULT '1' COMMENT 'Usuario activo 1 o no 0',
`last_login` DATETIME NOT NULL COMMENT 'Fecha de la última vez que inició sesión',
`notes` TEXT NOT NULL DEFAULT '' COMMENT 'Notas sobre el usuario',
`created_at` DATETIME NOT NULL COMMENT 'Fecha de creación del registro',
`updated_at` DATETIME NULL COMMENT 'Fecha de última modificación del registro',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


There are more tables, but these are the first two and it already crashes with:



#1005: Can't create table `tag` (Error: 150)


The script starts with SET FOREIGN_KEY_CHECKS = 0; and ends with SET FOREIGN_KEY_CHECKS = 1;



Any help would be appreciated, thanks!!










share|improve this question


















  • 3





    Create the user table first. It has to exist so the other table can refer to it

    – juergen d
    Nov 21 '18 at 10:53














0












0








0








I am making a script that reading some php files creates a SQL file. I have almost finished, but I am getting a MySQL error that I can't figure it out :(



This is the SQL code:



CREATE TABLE `tag` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Id único de cada tag',
`name` VARCHAR(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Nombre de la tag',
`id_user` INT(11) NOT NULL COMMENT 'Id del usuario',
`created_at` DATETIME NOT NULL COMMENT 'Fecha de creación del registro',
`updated_at` DATETIME NULL COMMENT 'Fecha de última modificación del registro',
PRIMARY KEY (`id`),
KEY `fk_tag_user_idx` (`id_user`),
CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Id único de un usuario',
`user` VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Nombre de usuario',
`pass` VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Contraseña del usuario',
`num_photos` INT(11) NOT NULL DEFAULT '0' COMMENT 'Número de fotos de un usuario',
`score` FLOAT NOT NULL DEFAULT '0' COMMENT 'Puntuación del usuario',
`active` TINYINT(1) NOT NULL DEFAULT '1' COMMENT 'Usuario activo 1 o no 0',
`last_login` DATETIME NOT NULL COMMENT 'Fecha de la última vez que inició sesión',
`notes` TEXT NOT NULL DEFAULT '' COMMENT 'Notas sobre el usuario',
`created_at` DATETIME NOT NULL COMMENT 'Fecha de creación del registro',
`updated_at` DATETIME NULL COMMENT 'Fecha de última modificación del registro',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


There are more tables, but these are the first two and it already crashes with:



#1005: Can't create table `tag` (Error: 150)


The script starts with SET FOREIGN_KEY_CHECKS = 0; and ends with SET FOREIGN_KEY_CHECKS = 1;



Any help would be appreciated, thanks!!










share|improve this question














I am making a script that reading some php files creates a SQL file. I have almost finished, but I am getting a MySQL error that I can't figure it out :(



This is the SQL code:



CREATE TABLE `tag` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Id único de cada tag',
`name` VARCHAR(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Nombre de la tag',
`id_user` INT(11) NOT NULL COMMENT 'Id del usuario',
`created_at` DATETIME NOT NULL COMMENT 'Fecha de creación del registro',
`updated_at` DATETIME NULL COMMENT 'Fecha de última modificación del registro',
PRIMARY KEY (`id`),
KEY `fk_tag_user_idx` (`id_user`),
CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Id único de un usuario',
`user` VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Nombre de usuario',
`pass` VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Contraseña del usuario',
`num_photos` INT(11) NOT NULL DEFAULT '0' COMMENT 'Número de fotos de un usuario',
`score` FLOAT NOT NULL DEFAULT '0' COMMENT 'Puntuación del usuario',
`active` TINYINT(1) NOT NULL DEFAULT '1' COMMENT 'Usuario activo 1 o no 0',
`last_login` DATETIME NOT NULL COMMENT 'Fecha de la última vez que inició sesión',
`notes` TEXT NOT NULL DEFAULT '' COMMENT 'Notas sobre el usuario',
`created_at` DATETIME NOT NULL COMMENT 'Fecha de creación del registro',
`updated_at` DATETIME NULL COMMENT 'Fecha de última modificación del registro',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


There are more tables, but these are the first two and it already crashes with:



#1005: Can't create table `tag` (Error: 150)


The script starts with SET FOREIGN_KEY_CHECKS = 0; and ends with SET FOREIGN_KEY_CHECKS = 1;



Any help would be appreciated, thanks!!







mysql mysql-error-1005






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 10:52









Iñigo GorosabelIñigo Gorosabel

2717




2717








  • 3





    Create the user table first. It has to exist so the other table can refer to it

    – juergen d
    Nov 21 '18 at 10:53














  • 3





    Create the user table first. It has to exist so the other table can refer to it

    – juergen d
    Nov 21 '18 at 10:53








3




3





Create the user table first. It has to exist so the other table can refer to it

– juergen d
Nov 21 '18 at 10:53





Create the user table first. It has to exist so the other table can refer to it

– juergen d
Nov 21 '18 at 10:53












2 Answers
2






active

oldest

votes


















2














I think the issue is of ordering of query, look into this line:



KEY `fk_tag_user_idx` (`id_user`),
CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


here you are referring to the table user, which is not created so far as the query to create user is below and which runs after first query.



So create the user table first and then tag table.






share|improve this answer
























  • Thanks, that was it... I thought setting foreign key check to 0 disabled ALL relation checks and as the table user was created inmediately after when I set it back to 1 it would all work. Thanks!!

    – Iñigo Gorosabel
    Nov 21 '18 at 11:37



















2














As Said, create user table first, or, if it's a problem, create all the tables without Foreign Key constraints and update them after all the create tables






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410532%2fgetting-1005-constraint-error-on-create-table%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    I think the issue is of ordering of query, look into this line:



    KEY `fk_tag_user_idx` (`id_user`),
    CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


    here you are referring to the table user, which is not created so far as the query to create user is below and which runs after first query.



    So create the user table first and then tag table.






    share|improve this answer
























    • Thanks, that was it... I thought setting foreign key check to 0 disabled ALL relation checks and as the table user was created inmediately after when I set it back to 1 it would all work. Thanks!!

      – Iñigo Gorosabel
      Nov 21 '18 at 11:37
















    2














    I think the issue is of ordering of query, look into this line:



    KEY `fk_tag_user_idx` (`id_user`),
    CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


    here you are referring to the table user, which is not created so far as the query to create user is below and which runs after first query.



    So create the user table first and then tag table.






    share|improve this answer
























    • Thanks, that was it... I thought setting foreign key check to 0 disabled ALL relation checks and as the table user was created inmediately after when I set it back to 1 it would all work. Thanks!!

      – Iñigo Gorosabel
      Nov 21 '18 at 11:37














    2












    2








    2







    I think the issue is of ordering of query, look into this line:



    KEY `fk_tag_user_idx` (`id_user`),
    CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


    here you are referring to the table user, which is not created so far as the query to create user is below and which runs after first query.



    So create the user table first and then tag table.






    share|improve this answer













    I think the issue is of ordering of query, look into this line:



    KEY `fk_tag_user_idx` (`id_user`),
    CONSTRAINT `fk_tag_user` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


    here you are referring to the table user, which is not created so far as the query to create user is below and which runs after first query.



    So create the user table first and then tag table.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 21 '18 at 10:57









    Mayank PandeyzMayank Pandeyz

    18.2k11738




    18.2k11738













    • Thanks, that was it... I thought setting foreign key check to 0 disabled ALL relation checks and as the table user was created inmediately after when I set it back to 1 it would all work. Thanks!!

      – Iñigo Gorosabel
      Nov 21 '18 at 11:37



















    • Thanks, that was it... I thought setting foreign key check to 0 disabled ALL relation checks and as the table user was created inmediately after when I set it back to 1 it would all work. Thanks!!

      – Iñigo Gorosabel
      Nov 21 '18 at 11:37

















    Thanks, that was it... I thought setting foreign key check to 0 disabled ALL relation checks and as the table user was created inmediately after when I set it back to 1 it would all work. Thanks!!

    – Iñigo Gorosabel
    Nov 21 '18 at 11:37





    Thanks, that was it... I thought setting foreign key check to 0 disabled ALL relation checks and as the table user was created inmediately after when I set it back to 1 it would all work. Thanks!!

    – Iñigo Gorosabel
    Nov 21 '18 at 11:37













    2














    As Said, create user table first, or, if it's a problem, create all the tables without Foreign Key constraints and update them after all the create tables






    share|improve this answer




























      2














      As Said, create user table first, or, if it's a problem, create all the tables without Foreign Key constraints and update them after all the create tables






      share|improve this answer


























        2












        2








        2







        As Said, create user table first, or, if it's a problem, create all the tables without Foreign Key constraints and update them after all the create tables






        share|improve this answer













        As Said, create user table first, or, if it's a problem, create all the tables without Foreign Key constraints and update them after all the create tables







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 11:10









        BingenBingen

        315




        315






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410532%2fgetting-1005-constraint-error-on-create-table%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            Origin of the phrase “under your belt”?