Results 1 to 2 of 2

Thread: SQL command to create relations between tables

  1. #1
    Join Date
    Apr 2004

    SQL command to create relations between tables

    I everybody!

    Does anybody know which is the SQL command to create relations between tables?

    Thank you very much!

  2. #2
    Join Date
    Apr 2005
    /* create 2 tables named PARENT and CHILD */

    CREATE TABLE parent( pfield1 int, pfileld2 char (30) );

    CREATE TABLE child ( cfield1 int, cfied2 char(20), cfield3 int );

    /* create the primary key for PARENT and CHILD, this field will represent a unique identifier for each of the table */
    ALTER TABLE parent add (primary key(pfield1));
    ALTER TABLE child add (primary key(cfield1));

    /* create the relation between PARENT and CHILD */
    ALTER TABLE child ADD ( FOREIGN KEY (cfield3) REFERENCES parent(pfield1));

    /* Insert data into parent and child tables */
    INSERT INTO parent values(1,'first row');
    INSERT INTO parent values(2,'2nd row');
    INSERT INTO parent values(3,'tird row');
    INSERT INTO child values(1,'first child',2);
    INSERT INTO child values(2,'2nd child',2);
    INSERT INTO child values(3,'third child',1);
    INSERT INTO child values(4,'4th child',1);

    /* make a query using relations */
    SELECT * FROM parent,child
    where parent.pfield1=child.cfield3

    Good luck in you lesson !

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts