Hello,
I am wondering in MySQL how can we know which table is a parent and which is a child?
thanks
Hello,
I am wondering in MySQL how can we know which table is a parent and which is a child?
thanks
Hi.
Typically the child table is the one having the foreign keys to their related parent.
So as far as I am concerned this is what I would rely on to tell.
Regards.
Sample code to play with
DROP DATABASE IF EXISTS test;
CREATE DATABASE IF NOT EXISTS test;
DROP TABLE IF EXISTS test.child;
DROP TABLE IF EXISTS test.parent;
CREATE TABLE IF NOT EXISTS test.parent (
parent_id INT AUTO_INCREMENT PRIMARY KEY,
parent_data_1 VARCHAR(10) UNIQUE NOT NULL,
parent_data_2 DECIMAL(7 , 2 ) CHECK ((parent_data_2 <> NULL)
AND (parent_data_2 BETWEEN 50.01 AND 99.99)),
parent_data_3 ENUM('Y', 'N', 'U')
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS test.child (
child_id INT PRIMARY KEY AUTO_INCREMENT,
child_data VARCHAR(20) UNIQUE NOT NULL,
parent_id INT,
CONSTRAINT FK_Child_Parent
FOREIGN KEY (parent_id)
REFERENCES parent (parent_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
) ENGINE=INNODB;
INSERT INTO test.child (child_data)
VALUES
('Lorem'),
('Ipsum'),
('and'),
('some'),
('more');
-- There is no Parent with ID 1000 and fails
-- Comment if needs be
-- INSERT INTO test.child (child_data, parent_id)
-- VALUES ('test',1000);
-- Lets insert a valid parent
INSERT INTO test.parent (parent_data_1)
VALUES ('p data 1'),('p data 2');
INSERT INTO test.parent (parent_data_1, parent_data_2)
VALUES ('p data 3',50.1),('p data 4',99.99);
-- This will run
INSERT INTO test.child (child_data, parent_id)
VALUES
('test 1',4),
('test 2',3),
('test 3',2),
('test 4',1),
('test 5',2),
('test 6',3),
('test 7',4);
SELECT
p.*, c.*
FROM
test.parent AS p
INNER JOIN
test.child AS c ON p.parent_id = c.parent_id
ORDER BY child_data DESC;