I don’t know how your business rule is defined, but when I look at it superficially I think it’s incorrect.
The relationship of pedido
is of 1...N
, you should have an entity pedido_produto
where the relationship between orders and products is made.
requested table
+----+------------+
| id | cliente_id |
+----+------------+
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
+----+------------+
table_product
+----+------------+
| id | descricao |
+----+------------+
| 1 | SMART TV |
| 2 | NOTEBOOK |
| 3 | SMARTPHONE |
+----+------------+
table_pedido_product
+-----------+------------+
| pedido_id | produto_id |
+-----------+------------+
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 3 |
| 3 | 1 |
+-----------+------------+
With the following DDL
:
CREATE TABLE tabela_cliente (
id INT AUTO_INCREMENT PRIMARY key,
nome VARCHAR(100)
);
CREATE TABLE tabela_pedido (
id INT AUTO_INCREMENT PRIMARY key,
cliente_id INT
);
CREATE TABLE tabela_produto (
id INT AUTO_INCREMENT PRIMARY key,
descricao VARCHAR(100)
);
CREATE TABLE tabela_pedido_produto (
pedido_id INT,
produto_id INT,
);
INSERT INTO tabela_cliente (nome) VALUES
('João'),
('José'),
('Maria'),
('Madalena');
INSERT INTO tabela_pedido (cliente_id) VALUES
(1),
(2),
(3),
(4);
INSERT INTO tabela_produto (descricao) VALUES
('SMARTPHONE'),
('SMARTV'),
('NOTEBOOK');
INSERT INTO tabela_pedido_produto (pedido_id, produto_id) VALUES
(1, 1),
(1, 2),
(2, 2),
(2, 3),
(3, 1),
(4, 2);
You would select orders by listing customers and products:
SELECT *
FROM tabela_pedido p
LEFT JOIN tabela_cliente c ON c.id = p.cliente_id
LEFT JOIN tabela_pedido_produto pp ON pp.pedido_id = p.id
LEFT JOIN tabela_produto pr ON pr.id = pp.produto_id
If for example, you want to get customer’s orders and products John, just add the clause WHERE
:
WHERE p.cliente_id = 1
Your structure has only one product per order? When you say it did not work, what does it mean? It was wrong? It would be interesting to ask the question examples of data and results you got and result you hoped to get.
– Pagotti