Search Results

Search found 1787 results on 72 pages for 'foreign'.

Page 1/72 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Should all foreign table references use foreign key constraints

    - by TecBrat
    Closely related to: Foreign key restrictions -> yes or no? I asked a question on SO and it led me to ask this here. If I'm faced with a choice of having a circular reference or just not enforcing the restraint, which is the better choice? In my particular case I have customers and addresses. I want an address to have a reference to a customer and I want each customer to have a default billing address id and a default shipping address id. I might query for all addresses that have a certain customer ID or I might query for the address with the ID that matches the default shipping or billing address ids. I'm not sure yet how the constraints (or lack of) will effect the system as my application and it's data age.

    Read the article

  • sql foreign keys

    - by Paul Est
    I was create tables with the syntax in phpmyadmin: DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS info; CREATE TABLE users ( user_id int unsigned NOT NULL auto_increment, email varchar(100) NOT NULL default '', pwd varchar(32) NOT NULL default '', isAdmin int(1) unsigned NOT NULL, PRIMARY KEY (user_id) ) TYPE=INNODB; CREATE TABLE info ( info_id int unsigned NOT NULL auto_increment, first_name varchar(100) NOT NULL default '', last_name varchar(100) NOT NULL default '', address varchar(300) NOT NULL default '', zipcode varchar(100) NOT NULL default '', personal_phone varchar(100) NOT NULL default '', mobilephone varchar(100) NOT NULL default '', faxe varchar(100) NOT NULL default '', email2 varchar(100) NOT NULL default '', country varchar(100) NOT NULL default '', sex varchar(1) NOT NULL default '', birth varchar(1) NOT NULL default '', email varchar(100) NOT NULL default '', PRIMARY KEY (info_id), FOREIGN KEY (email) REFERENCES users(email) ON UPDATE CASCADE ON DELETE CASCADE ) TYPE=INNODB; But shows the error "#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TYPE=INNODB' at line 11 " If i remove the TYPE=INNODB in the end of create the tables, it will show the error "#1005 - Can't create table 'curriculo.info' (errno: 150) ".

    Read the article

  • Problems getting foreign keys working in MySQL

    - by thehuby
    I've been trying to get a delete to cascade and it just doesn't seem to work. I'm sure I am missing something obvious, can anyone help me find it? I would expect a delete on the 'articles' table to trigger a delete on the corresponding rows in the 'article_section_lt' table. CREATE TABLE articles ( id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, url_stub VARCHAR(255) NOT NULL UNIQUE, h1 VARCHAR(60) NOT NULL UNIQUE, title VARCHAR(60) NOT NULL, description VARCHAR(150) NOT NULL, summary VARCHAR(150) NOT NULL DEFAULT "", html_content TEXT, date DATE NOT NULL, updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=INNODB; CREATE TABLE article_sections ( /* blog, news etc */ id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, url_stub VARCHAR(255) NOT NULL UNIQUE, h1 VARCHAR(60) NOT NULL, title VARCHAR(60) NOT NULL, description VARCHAR(150) NOT NULL, summary VARCHAR(150) NOT NULL DEFAULT "", html_content TEXT NOT NULL DEFAULT "" )ENGINE=INNODB; CREATE TABLE article_section_lt ( fk_article_id INTEGER UNSIGNED NOT NULL REFERENCES articles(id) ON DELETE CASCADE, fk_article_section_id INTEGER UNSIGNED NOT NULL )ENGINE=INNODB;

    Read the article

  • SQL - Two foreign keys that have a dependency between them

    - by Brian
    The current structure is as follows: Table RowType: RowTypeID Table RowSubType: RowSubTypeID FK_RowTypeID Table ColumnDef: FK_RowTypeID FK_RowSubTypeID (nullable) In short, I'm mapping column definitions to rows. In some cases, those rows have subtype(s), which will have column definitions specific to them. Alternatively, I could hang those column definitions that are specific to subtypes off their own table, or I could combine the data in RowType and RowSubType into one table and work with a single ID, but I'm not sure either is a better solution (if anything, I'd lean towards the latter, as we mostly end up pulling ColumnDefs for a given RowType/RowSubType). Is the current design SQL Blasphemy? If I keep the current structuree, how do I maintain that if RowSubTypeID is specified in ColumnDef, that it must correspond to the RowType specified by RowTypeID? Should I try to enforce this with a trigger or am I missing a simple redesign that would solve the problem?

    Read the article

  • Rejuvenated: Script Creates and Drops for Candidate Keys and Referencing Foreign Keys

    - by Adam Machanic
    Once upon a time it was 2004, and I wrote what I have to say was a pretty cool little script . (Yes, I know the post is dated 2006, but that's because I dropped the ball and failed to back-date the posts when I moved them over here from my prior blog space.) The impetus for creating this script was (and is) simple: Changing keys can be a painful experience. Sometimes you want to make a clustered key nonclustered, or a nonclustered key clustered. Or maybe you want to add a column to the key. Or remove...(read more)

    Read the article

  • Should foreign keys become table primary key?

    - by Carvell Fenton
    Hello again, I have a table (session_comments) with the following fields structure: student_id (foreign key to students table) session_id (foreign key to sessions table) session_subject_ID (foreign key to session_subjects table) user_id (foreign key to users table) comment_date_time comment Now, the combination of student_id, session_id, and session_subject_id will uniquely identify a comment about that student for that session subject. Given that combined they are unique, even though they are foreign keys, is there an advantage to me making them the combined primary key for that table? Thanks again.

    Read the article

  • Three level database - foreign keys

    - by poke
    I have a three level database with the following structure (simplified to only show the primary keys): Table A: a_id Table B: a_id, b_id Table C: a_id, b_id, c_id So possible values for table C would be something like this: a_id b_id c_id 1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 2 1 1 2 2 1 2 2 2 ... I am now unsure, how foreign keys should be set; or if they should be set for the primary keys at all. My idea was to have a foreign key on table B B.a_id -> A.a_id, and two foreign key on C C.a_id -> A.a_id and ( C.a_id, C.b_id ) -> ( B.a_id, B.b_id ). Is that the way I should set up the foreign keys? Is the foreign key from C->A necessary? Or do I even need foreign keys at all given that all those columns are part of the primary keys? Thanks.

    Read the article

  • MySQL whats wrong with my foreign keys?

    - by Skiy
    Hello, what is wrong with the two foreign keys which I have marked with comments? create database db; use db; create table Flug( Flugbez varchar(20), FDatum Date, Ziel varchar(20), Flugzeit int, Entfernung int, Primary Key (Flugbez, FDatum)); create table Flugzeugtyp( Typ varchar(20), Hersteller varchar(20), SitzAnzahl int, Reisegeschw int, primary key (Typ) ); create table flugzeug( Typ varchar(20), SerienNr int, AnschDatum Date, FlugStd int, primary key(Typ,SerienNr), foreign key(Typ) references Flugzeugtyp(Typ)); create table Abflug( Flugbez varchar(20), FDatum Date, Typ varchar(20), Seriennr int, Kaptaen varchar(20), Primary key(Flugbez,FDatum,Typ,SerienNr), Foreign key(Flugbez) references Flug(Flugbez), -- Foreign key(FDatum) references Flug(FDatum), Foreign key(Typ) references Flugzeugtyp(Typ) -- ,Foreign key(SerienNr) references Flugzeug(SerienNr) ); When I uncomment these, I get: ERROR 1005 (HY000): Can't create table 'db.abflug' (errno: 150)

    Read the article

  • OperationalError: foreign key mismatch

    - by Niek de Klein
    I have two tables that I'm filling, 'msrun' and 'feature'. 'feature' has a foreign key pointing to the 'msrun_name' column of the 'msrun' table. Inserting in the tables works fine. But when I try to delete from the 'feature' table I get the following error: pysqlite2.dbapi2.OperationalError: foreign key mismatch From the rules of foreign keys in the manual of SQLite: - The parent table does not exist, or - The parent key columns named in the foreign key constraint do not exist, or - The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or - The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns. I can see nothing that I'm violating. My create tables look like this: DROP TABLE IF EXISTS `msrun`; -- ----------------------------------------------------- -- Table `msrun` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `msrun` ( `msrun_name` VARCHAR(40) PRIMARY KEY NOT NULL , `description` VARCHAR(500) NOT NULL ); DROP TABLE IF EXISTS `feature`; -- ----------------------------------------------------- -- Table `feature` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `feature` ( `feature_id` VARCHAR(40) PRIMARY KEY NOT NULL , `intensity` DOUBLE NOT NULL , `overallquality` DOUBLE NOT NULL , `charge` INT NOT NULL , `content` VARCHAR(45) NOT NULL , `msrun_msrun_name` VARCHAR(40) NOT NULL , CONSTRAINT `fk_feature_msrun1` FOREIGN KEY (`msrun_msrun_name` ) REFERENCES `msrun` (`msrun_name` ) ON DELETE NO ACTION ON UPDATE NO ACTION); CREATE UNIQUE INDEX `id_UNIQUE` ON `feature` (`feature_id` ASC); CREATE INDEX `fk_feature_msrun1` ON `feature` (`msrun_msrun_name` ASC); As far as I can see the parent table exists, the foreign key is pointing to the right parent key, the parent key is a primary key and the foreign key specifies the primary key column. The script that produces the error: from pysqlite2 import dbapi2 as sqlite import parseFeatureXML connection = sqlite.connect('example.db') cursor = connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") inputValues = ('example', 'description') cursor.execute("INSERT INTO `msrun` VALUES(?, ?)", inputValues) featureXML = parseFeatureXML.Reader('../example_scripts/example_files/input/featureXML_example.featureXML') for feature in featureXML.getSimpleFeatureInfo(): inputValues = (featureXML['id'], featureXML['intensity'], featureXML['overallquality'], featureXML['charge'], featureXML['content'], 'example') # insert the values into msrun using ? for sql injection safety cursor.execute("INSERT INTO `feature` VALUES(?,?,?,?,?,?)", inputValues) connection.commit() for feature in featureXML.getSimpleFeatureInfo(): cursor.execute("DELETE FROM `feature` WHERE feature_id = ?", (str(featureXML['id']),))

    Read the article

  • Pros and cons of programmatically enforcing foreign key than in database

    - by Jeffrey
    It is causing so much trouble in terms of development just by letting database enforcing foreign key. Especially during unit test I can’t drop table due to foreign key constrains, I need to create table in such an order that foreign key constrain warning won’t get triggered. In reality I don’t see too much point of letting database enforcing the foreign key constrains. If the application has been properly designed there should not be any manual database manipulation other than select queries. I just want to make sure that I am not digging myself into a hole by not having foreign key constrains in database and leaving it solely to the application’s responsibility. Am I missing anything? P.S. my real unit tests (not those that use mocking) will drop existing tables if the structure of underlying domain object has been modified.

    Read the article

  • Working with foreign keys - cannot insert

    - by Industrial
    Hi everyone! Doing my first tryouts with foreign keys in a mySQL database and are trying to do a insert, that fails for this reason: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Does this mean that foreign keys restrict INSERTS as well as DELETES and/or UPDATES on each table that is enforced with foreign keys relations? Thanks! Updated description: Products ---------------------------- id | type ---------------------------- 0 | 0 1 | 3 ProductsToCategories ---------------------------- productid | categoryid ---------------------------- 0 | 0 1 | 1 Product table has following structure CREATE TABLE IF NOT EXISTS `alpha`.`products` ( `id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT , `type` TINYINT(2) UNSIGNED NOT NULL DEFAULT 0 , PRIMARY KEY (`id`) , CONSTRAINT `prodsku` FOREIGN KEY (`id` ) REFERENCES `alpha`.`productsToSku` (`product` ) ON DELETE CASCADE, ON UPDATE CASCADE) ENGINE = InnoDB;

    Read the article

  • Poll Results: Foreign Key Constraints

    - by Darren Gosbell
    A few weeks ago I did the following post asking people – if they used foreign key constraints in their star schemas. The poll is still open if you are interested in adding to it, but here is what the chart looks like as of today. (at the bottom of the poll itself there is a link to the live results, unfortunately I cannot link the live results in here as the blogging platform blocks the required javascript)   Interestingly the results are fairly even. Of the 78 respondents, fractionally over half at least aim to start with referential integrity in their star schemas. I did not want to influence the results by sharing my opinion, but my personal preference is to always aim to have foreign key constraints. But at the same time, I am pragmatic about it, I do have projects where for various reasons some constraints are not defined. And I also have other designs that I have inherited, where it would just be too much work to go back and add foreign key constraints. If you are going to implement foreign keys in your star schema, they really need to be there at the start. In fact this poll was was the result of a feature request for BIDSHelper asking for a feature to check for null/missing foreign keys and I am entirely convinced that BIDS is the wrong place for this sort of functionality. BIDS is a design tool, your data needs to be constantly checked for consistency. It's not that I think that it's impossible to get a design working without foreign key constraints, but I like the idea of failing as soon as possible if there is an error and enforcing foreign key constraints lets me "fail early" if there are constancy issues with my data. By far the biggest concern with foreign keys is performance and I suppose I'm curious as to how often people actually measure and quantify this. I worked on a project a number of years ago that had very large data volumes and we did find that foreign key constraints did have a measurable impact, but what we did was to disable the constraints before loading the data, then enabled and checked them afterwards. This saved as time (although not as much as not having constraints at all), but still let us know early in the process if there were any consistency issues. For the people that do not have consistent data, if you have ETL processes that you control that are building your star schema which you also control, then to be blunt you only have yourself to blame. It is the job of the ETL process to make the data consistent. There are techniques for handling situations like missing data as well as  early and late arriving data. Ralph Kimball's book – The Data Warehouse Toolkit goes through some design patterns for handling data consistency. Having foreign key relationships can also help the relational engine to optimize queries as noted in this recent blog post by Boyan Penev

    Read the article

  • MySQL Error 1452 - Cannot add or update a child row: a foreign key constraint fails

    - by dscher
    I've looked at other people's questions on this topic but can't seem to find where my error is coming from. Any help would be greatly appreciated. I'm including as much as I can think of that might help find the problem: CREATE TABLE stocks ( id INT AUTO_INCREMENT NOT NULL, user_id INT(11) UNSIGNED NOT NULL, ticker VARCHAR(20) NOT NULL, name VARCHAR(20), rating INT(11), position ENUM("strong buy", "buy", "sell", "strong sell", "neutral"), next_look DATE, privacy ENUM("public", "private"), PRIMARY KEY(id), FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `stocks_tags` ( `stock_id` INT NOT NULL, `tag_id` INT NOT NULL, PRIMARY KEY (`stock_id`,`tag_id`), KEY `fk_stock_tag` (`tag_id`), KEY `fk_tag_stock` (`stock_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `stocks_tags` ADD CONSTRAINT `fk_stock_tag` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fk_tag_stock` FOREIGN KEY (`stock_id`) REFERENCES `stocks` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; CREATE TABLE tags( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, tags VARCHAR(30), UNIQUE(tags) ) ENGINE=INNODB DEFAULT CHARSET=utf8; And the error I'm getting: Database_Exception [ 1452 ]: Cannot add or update a child row: a foreign key constraint fails (`ddmachine`.`stocks_tags`, CONSTRAINT `fk_stock_tag` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) [ INSERT INTO `stocks_tags` (`stock_id`, `tag_id`) VALUES (19, 'cash') ] I did see that someone else had a similar problem based on their enum columns but don't think that's it.

    Read the article

  • Foreign keys with Rails' ActiveRecord::Migration?

    - by Earlz
    Hello, I'm new to Ruby on Rails (I know Ruby just decently though) and looking at the Migration tools, it sounds really awesome. Database schemas can finally (easily) go in source control. Now my problem with it. When using Postgres as the database, it does not setup foreign keys. I would like the benefits of foreign keys in my schema such as referential integrity. So how do I apply foreign keys with Migrations?

    Read the article

  • Foreign keys vs partitioning

    - by Industrial
    Hi! Since foreign keys are not supported by partitioned mySQL databases for the moment, I would like to hear some pro's and con's for a read-heavy application that will handle around 1-400 000 rows per table. Unfortunately, I dont have enough experience yet in this area to make the conclusion by myself... Thanks a lot! References: http://stackoverflow.com/questions/1537219/how-to-handle-foreign-key-while-partitioning http://stackoverflow.com/questions/2496140/mysql-partitioning-with-foreign-keys

    Read the article

  • Foreign key,local key?

    - by user198729
    CREATE TABLE products ( id integer unsigned auto_increment primary key ) ENGINE=INNODB; CREATE TABLE orders ( id integer PRIMARY KEY auto_increment, product_id integer unsigned, quantity integer, INDEX product_id_idx (product_id), FOREIGN KEY (product_id) REFERENCES products (id) ) ENGINE=INNODB; Here the products and orders obviously have some kind of relation--foreign key relation. Also a coin has two sides,so I'm doubting how do we say which table is the foreign key side or local key side?

    Read the article

  • Foreign keys in MySQL?

    - by icco
    I have been slowly learning SQL the last few weeks. I've picked up all of the relational algebra and the basics of how relational databases work. What I'm trying to do now is learn how it's implemented. A stumbling block I've come across in this, is foreign keys in MySQL. I can't seem to find much about the other than that they exist in the InnoDB storage schema that MySQL has. What is a simple example of foreign keys implemented in MySQL? Here's part of a schema I wrote that doesn't seem to be working if you would rather point out my flaw than show me a working example. CREATE TABLE `posts` ( `pID` bigint(20) NOT NULL auto_increment, `content` text NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `uID` bigint(20) NOT NULL, `wikiptr` bigint(20) default NULL, `cID` bigint(20) NOT NULL, PRIMARY KEY (`pID`), Foreign Key(`cID`) references categories, Foreign Key(`uID`) references users ) ENGINE=InnoDB;

    Read the article

  • Please help me to create a insert query (error of foreign key constrant)

    - by Rajesh Rolen- DotNet Developer
    I want to move data from one database's table to another database's table its giving me foreign key error. please tell me how can i insert all those data which is valid except those rows who have error of foreign key. i am using sql server 2005 My query is : SET IDENTITY_INSERT City ON INSERT INTO City ([cityid],[city],[country],[state],[cityinfo] ,[enabled],[countryid],[citycode],[stateid],[latitude],[longitude]) SELECT [cityid],[city],[country],[state],[cityinfo] ,[enabled],[countryid],[citycode],[stateid],[latitude],[longitude] FROM TD.DBo.City getting this error: The INSERT statement conflicted with the FOREIGN KEY constraint "FK__city__countryid__3E52440B". The conflict occurred in database "schoolHigher", table "dbo.country", column 'countryId'. please tell how can i move those data whose foreign key is valid.

    Read the article

  • Foreign Key Relationships and "belongs to many"

    - by jan
    I have the following model: S belongs to T T has many S A,B,C,D,E (etc) have 1 T each, so the T should belong to each of A,B,C,D,E (etc) At first I set up my foreign keys so that in A, fk_a_t would be the foreign key on A.t to T(id), in B it'd be fk_b_t, etc. Everything looks fine in my UML (using MySQLWorkBench), but generating the yii models results in it thinking that T has many A,B,C,D (etc) which to me is the reverse. It sounds to me like either I need to have A_T, B_T, C_T (etc) tables, but this would be a pain as there are a lot of tables that have this relationship. I've also googled that the better way to do this would be some sort of behavior, such that A,B,C,D (etc) can behave as a T, but I'm not clear on exactly how to do this (I will continue to google more on this) What do you think is the better solution? UML: Here's the DDL (auto generated). Just pretend that there is more than 3 tables referencing T. -- ----------------------------------------------------- -- Table `mydb`.`T` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`T` ( `id` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY (`id`) ) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`S` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`S` ( `id` INT NOT NULL AUTO_INCREMENT , `thing` VARCHAR(45) NULL , `t` INT NOT NULL , PRIMARY KEY (`id`) , INDEX `fk_S_T` (`id` ASC) , CONSTRAINT `fk_S_T` FOREIGN KEY (`id` ) REFERENCES `mydb`.`T` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`A` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`A` ( `id` INT NOT NULL AUTO_INCREMENT , `T` INT NOT NULL , `stuff` VARCHAR(45) NULL , `bar` VARCHAR(45) NULL , `foo` VARCHAR(45) NULL , PRIMARY KEY (`id`) , INDEX `fk_A_T` (`T` ASC) , CONSTRAINT `fk_A_T` FOREIGN KEY (`T` ) REFERENCES `mydb`.`T` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`B` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`B` ( `id` INT NOT NULL AUTO_INCREMENT , `T` INT NOT NULL , `stuff2` VARCHAR(45) NULL , `foobar` VARCHAR(45) NULL , `other` VARCHAR(45) NULL , PRIMARY KEY (`id`) , INDEX `fk_A_T` (`T` ASC) , CONSTRAINT `fk_A_T` FOREIGN KEY (`T` ) REFERENCES `mydb`.`T` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`C` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`C` ( `id` INT NOT NULL AUTO_INCREMENT , `T` INT NOT NULL , `stuff3` VARCHAR(45) NULL , `foobar2` VARCHAR(45) NULL , `other4` VARCHAR(45) NULL , PRIMARY KEY (`id`) , INDEX `fk_A_T` (`T` ASC) , CONSTRAINT `fk_A_T` FOREIGN KEY (`T` ) REFERENCES `mydb`.`T` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB;

    Read the article

  • Foreign key not working in MySQL: Why can I INSERT a value that's not in the foreign column?

    - by stalepretzel
    I've created a table in MySQL: CREATE TABLE actions ( A_id int NOT NULL AUTO_INCREMENT, type ENUM('rate','report','submit','edit','delete') NOT NULL, Q_id int NOT NULL, U_id int NOT NULL, date DATE NOT NULL, time TIME NOT NULL, rate tinyint(1), PRIMARY KEY (A_id), CONSTRAINT fk_Question FOREIGN KEY (Q_id) REFERENCES questions(P_id), CONSTRAINT fk_User FOREIGN KEY (U_id) REFERENCES users(P_id)); This created the table I wanted just fine (although a "DESCRIBE actions;" command showed me that the foreign keys were keys of type MUL, and I'm not sure what this means). However, when I try to enter a Q_id or a U_id that does not exist in the questions or users tables, MySQL still allows these values. What did I do wrong? How can I prevent a table with a foreign key from accepting invalid data? If I add TYPE=InnoDB to the end, I get an error: ERROR 1005 (HY000): Can't create table './quotes/actions.frm' (errno: 150) Why might that happen? I'm told that it's important to enforce data integrity with functional foreign keys, but also that InnoDB should not be used with MySQL. What do you recommend?

    Read the article

  • Creating a foreign key in MySQL produces error:

    - by SnOrfus
    I'm trying to create a foreign key on a table in MySQL and I'm getting a strange error that there seems to be little info about in any of my searches. I'm creating the key with this (emitted from mysql workbench 5.2): ALTER TABLE `db`.`appointment` ADD CONSTRAINT `FK_appointment_CancellationID` FOREIGN KEY (`CancellationID` ) REFERENCES `db`.`appointment_cancellation` (`ID` ) ON DELETE NO ACTION ON UPDATE NO ACTION , ADD INDEX `FK_appointment_CancellationID` (`CancellationID` ASC) ; at which point I get the error: ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (alarmtekcore., CONSTRAINT FK_lead_appointment_CancellationID FOREIGN KEY (CancellationID) REFERENCES lead_appointment_cancellation (`) I've checked here but there's no data in the table.

    Read the article

  • MySQL Removing Some Foreign keys

    - by Drew
    I have a table whose primary key is used in several other tables and has several foreign keys to other tables. CREATE TABLE location ( locationID INT NOT NULL AUTO_INCREMENT PRIMARY KEY ... ) ENGINE = InnoDB; CREATE TABLE assignment ( assignmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, locationID INT NOT NULL, FOREIGN KEY locationIDX (locationID) REFERENCES location (locationID) ... ) ENGINE = InnoDB; CREATE TABLE assignmentStuff ( ... assignmentID INT NOT NULL, FOREIGN KEY assignmentIDX (assignmentID) REFERENCES assignment (assignmentID) ) ENGINE = InnoDB; The problem is that when I'm trying to drop one of the foreign key columns (ie locationIDX) it gives me an "ERROR 1025 (HY000): Error on rename" error. How can I drop the column in the assignment table above without getting this error?

    Read the article

  • foreign key and index issue

    - by George2
    Hello everyone, I am using SQL Server 2008 Enterprise. I have a table and one of its column is referring to another column in another table (in the same database) as foreign key, here is the related SQL statement, in more details, column [AnotherID] in table [Foo] refers to another table [Goo]'s column [GID] as foreign key. [GID] is primary key and clustered index on table [Goo]. My question is, in this way, if I do not create index on [AnotherID] column on [Foo] explicitly, will there be an index created automatically for [AnotherID] column on [Foo] -- because its foreign key reference column [GID] on table [Goo] already has primary clustered key index? CREATE TABLE [dbo].[Foo]( [ID] [bigint] IDENTITY(1,1) NOT NULL, [AnotherID] [int] NULL, [InsertTime] [datetime] NULL CONSTRAINT DEFAULT (getdate()), CONSTRAINT [PK_Foo] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] ALTER TABLE [dbo].[Foo] WITH CHECK ADD CONSTRAINT [FK_Foo] FOREIGN KEY([Goo]) REFERENCES [dbo].[Goo] ([GID]) ALTER TABLE [dbo].[Foo] CHECK CONSTRAINT [FK_Foo] thanks in advance, George

    Read the article

  • When to use a foreign key in MySQL

    - by Mel
    Is there official guidance or a threshold to indicate when it is best practice to use a foreign key in a MySQL database? Suppose you created a table for movies. One way to do it is to integrate the producer and director data into the same table. (movieID, movieName, directorName, producerName). However, suppose most directors and producers have worked on many movies. Would it be best to create two other tables for producers and directors, and use a foreign key in the movie table? When does it become best practice to do this? When many of the directors and producers are appearing several times in the column? Or is it best practice to employ a foreign key approach at the start? While it seems more efficient to use a foreign key, it also raises the complexity of the database. So when does the trade off between complexity and normalization become worth it? I'm not sure if there is a threshold or a certain number of cell repetitions that makes it more sensible to use a foreign key. I'm thinking about a database that will be used by hundreds of users, many concurrently. Many thanks!

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >