I point you to use a link table and put the AUTO_INCREMENT
in this table with foreign key for the other two. In each of the main tables you would create a TRIGGER
which would fill the link table at the time of insertion. Then just select the data as described in query
down below:
Schema (Mysql v5.7)
CREATE TABLE tabela1 (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
campo VARCHAR(3)
);
CREATE TRIGGER trg_i_tabela1
AFTER INSERT ON tabela1
FOR EACH ROW
INSERT INTO vinculo(id_tabela1) VALUES(NEW.id);
CREATE TABLE tabela2 (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
campo VARCHAR(3)
);
CREATE TRIGGER trg_i_tabela2
AFTER INSERT ON tabela2
FOR EACH ROW
INSERT INTO vinculo(id_tabela2) VALUES(NEW.id);
CREATE TABLE vinculo (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
id_tabela1 INTEGER,
id_tabela2 INTEGER,
FOREIGN KEY fk_vinculo_tabela1(id_tabela1) REFERENCES tabela1(id),
FOREIGN KEY fk_vinculo_tabela2(id_tabela2) REFERENCES tabela2(id)
);
INSERT INTO tabela1(campo) VALUES('a1');
INSERT INTO tabela1(campo) VALUES('b1');
INSERT INTO tabela2(campo) VALUES('a2');
INSERT INTO tabela2(campo) VALUES('b2');
INSERT INTO tabela1(campo) VALUES('c1');
INSERT INTO tabela2(campo) VALUES('c2');
Query
SELECT v.id,
COALESCE(t1.campo, t2.campo) AS campo
FROM vinculo v
LEFT JOIN tabela1 t1 ON t1.id = v.id_tabela1
LEFT JOIN tabela2 t2 ON t2.id = v.id_tabela2
ORDER BY v.id;
Upshot
| id | campo |
| --- | ----- |
| 1 | a1 |
| 2 | b1 |
| 3 | a2 |
| 4 | b2 |
| 5 | c1 |
| 6 | c2 |
See working on DB Fiddle.
It makes no sense what you want to do. It wants to explain to us what the root problem is to suggest solutions?
– Sorack
I’m doing maintenance on a legacy system. They currently sell a Product A in which order information is saved in the Order A table. The ID of this table is sent to the payment gateway and that ID is used to identify the payment. Now the customer wants to sell a Product B, but not to save the information in the Order A table, because it was created specifically for Product A. So I thought to create a Order B table, but the records ID cannot be equal to the Order A table ID, so I thought I’d "share" the auto increment between the two tables.
– Gustavo Primo