I am working with a MySQL backend (version 5.7.19), and a LibreOffice Base frontend(version 7.0.6.2 x64) on 64-bit Windows. I have a table that lists personnel with a primary key id. I also have a workorders table that has an "entered by" field and a "reviewed by" field, both of which need to store the id of the personnel who complete those tasks. If I wanted to have two foreign keys in one table pointing to the same table's primary key, what would my SELECT statement need to look like?
In my case, I have a table 'personnel' with two fields with ID as the primary key, thus:
ID | Name |
---|---|
1 | John Smith |
2 | John Adams |
3 | Samuel Adams |
which can be created and populated thus:
CREATE TABLE orders(
workorder int(10) unsigned NOT NULL AUTO_INCREMENT,
entered_by int(10) unsigned NOT NULL,
reviewed_by int(10) unsigned NOT NULL,
PRIMARY KEY (workorder),
FOREIGN KEY (entered_by) REFERENCES personnel(id),
FOREIGN KEY (reviewed_by) REFERENCES personnel(id)
);
ALTER TABLE orders AUTO_INCREMENT = 1;
INSERT INTO personnel(name) VALUES('John Smith');
INSERT INTO personnel(name) VALUES('John Adams');
INSERT INTO personnel(name) VALUES('Samuel Adams');
Also, a table 'orders' with three fields with entered_by and reviewed_by as foreign keys to personnel.id
workorder | entered_by | reviewed_by |
---|---|---|
1 | 2 | 3 |
2 | 3 | 1 |
which can be created and populated thus:
CREATE TABLE orders(
workorder int(10) unsigned NOT NULL AUTO_INCREMENT,
entered_by int(10) unsigned NOT NULL,
reviewed_by int(10) unsigned NOT NULL,
PRIMARY KEY (workorder),
FOREIGN KEY (entered_by) REFERENCES personnel(id),
FOREIGN KEY (reviewed_by) REFERENCES personnel(id)
);
INSERT INTO orders(entered_by, reviewed_by) VALUES (2,3);
INSERT INTO orders(entered_by, reviewed_by) VALUES (3,1);
I know how to
SELECT workorder, personnel.name AS entered
FROM orders JOIN personnel
ON personnel.id = orders.entered_by
ORDER BY orders.workorder;
which results in
workorder | entered |
---|---|
1 | John Adams |
2 | Samuel Adams |
and how to
SELECT workorder, personnel.name AS entered
FROM orders JOIN personnel
ON personnel.id = orders.entered_by
ORDER BY orders.workorder;
which yields:
workorder | reviewed |
---|---|
1 | Samuel Adams |
2 | John Smith |
but I'm not sure how to put them into a single query (that I can use in a query form in Base), so that it will display:
workorder | entered | reviewed |
---|---|---|
1 | John Adams | Samuel Adams |
2 | Samuel Adams | John Smith |