How to create relationships in MySQL

If the tables are innodb you can create it like this: CREATE TABLE accounts( account_id INT NOT NULL AUTO_INCREMENT, customer_id INT( 4 ) NOT NULL , account_type ENUM( ‘savings’, ‘credit’ ) NOT NULL, balance FLOAT( 9 ) NOT NULL, PRIMARY KEY ( account_id ), FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ) ENGINE=INNODB; You have to specify … Read more

How to change the foreign key referential action? (behavior)

Old question but adding answer so that one can get help Its two step process: Suppose, a table1 has a foreign key with column name fk_table2_id, with constraint name fk_name and table2 is referred table with key t2 (something like below in my diagram). table1 [ fk_table2_id ] –> table2 [t2] First step, DROP old … Read more

Add Foreign Key relationship between two Databases

You would need to manage the referential constraint across databases using a Trigger. Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception. Example: Create Trigger dbo.MyTableTrigger ON dbo.MyTable, … Read more

Django: Set foreign key using integer?

Yep: employee = Employee(first_name=”Name”, last_name=”Name”) employee.type_id = 4 employee.save() ForeignKey fields store their value in an attribute with _id at the end, which you can access directly to avoid visiting the database. The _id version of a ForeignKey is a particularly useful aspect of Django, one that everyone should know and use from time to … Read more

What is a proper naming convention for MySQL FKs?

In MySQL, there is no need to give a symbolic name to foreign key constraints. If a name is not given, InnoDB creates a unique name automatically. In any case, this is the convention that I use: fk_[referencing table name]_[referenced table name]_[referencing field name] Example: CREATE TABLE users( user_id int, name varchar(100) ); CREATE TABLE … Read more

Delete rows with foreign key in PostgreSQL

To automate this, you could define the foreign key constraint with ON DELETE CASCADE. I quote the the manual for foreign key constraints: CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well. Look up the current FK definition like this: SELECT pg_get_constraintdef(oid) AS constraint_def FROM pg_constraint … Read more

Foreign keys in mongo?

How to design table like this in mongodb? First, to clarify some naming conventions. MongoDB uses collections instead of tables. I think there are no foreign keys! Take the following model: student { _id: ObjectId(…), name: ‘Jane’, courses: [ { course: ‘bio101’, mark: 85 }, { course: ‘chem101’, mark: 89 } ] } course { … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)