Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reference a different column in the same table?

If a blog has a 'categories' table such as the following:

CREATE TABLE categories
(
  id INTEGER PRIMARY KEY AUTO_INCREMENT,
  parent_id INTEGER NOT NULL,
  name VARCHAR(30) NOT NULL,
  description TEXT,
  count INTEGER NOT NULL DEFAULT 0
);

And if the parent_id field is intended to refer to the 'id' field of the categories table, then how could I add a constraint that would ensure that values inserted into parent_id references the id field?

I simply want to make sure that only category id values that exist can be used as a parent of a newly inserted category.

like image 402
Jim Johnson Avatar asked Jul 12 '12 20:07

Jim Johnson


People also ask

Can a table have two foreign keys from same table?

A table can have multiple foreign keys based on the requirement.

Can a column reference two tables?

In SQL can a single column in a table reference multiple tables - no this is not possible. A foreign key always references one target table (and one table only).

Can a foreign key have multiple columns?

MySQL allows us to add a FOREIGN KEY constraint on multiple columns in a table. The condition is that each Foreign Key in the child table must refer to the different parent table.

What is it called when a column has a relationship to another column in the same table?

A term you'll see used for this type of table is hierarchical data/table/queries – the table represents a hierarchy, or parent/child relationship of some form.


1 Answers

Yes, you can reference a column in the same table.

But that column should be nullable otherwise you can't insert the first record.

CREATE TABLE categories
(
  id INTEGER PRIMARY KEY AUTO_INCREMENT,
  parent_id INTEGER NULL,
  name VARCHAR(30) NOT NULL,
  description TEXT,
  count INTEGER NOT NULL DEFAULT 0,
  FOREIGN KEY (parent_id) REFERENCES categories(id)
);

Note that after the REFERENCES keyword the table name is not optional, so you must specify it even if you are referencing a column in the same table. From the documentation:

reference_definition:
    REFERENCES tbl_name (index_col_name,...)
      [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]
      [ON DELETE reference_option]
      [ON UPDATE reference_option]

See it working online: sqlfiddle

like image 78
Mark Byers Avatar answered Sep 26 '22 08:09

Mark Byers