'How to join 4 tables with mysql

Sorry, now here is the code, basically, the first query returns me a tab which contains fk_id_produto, i wanted to join it with thee second one with the id_pedido

(SELECT fk_id_produto,fk_id_pedido, descricao_produto, valor_produto 
FROM Pedido_Produto
INNER JOIN Produto ON pedido_produto.fk_id_produto = produto.id_produto);

INNER JOIN ON

(SELECT id_cliente,nome_cliente,id_pedido,valor_pedido,data_do_pedido A
FROM Cliente 
INNER JOIN Pedido ON cliente.id_cliente = pedido.fk_id_cliente);

Result of the first part of the query

Result of the second part of the query



Solution 1:[1]

You can just do a join with the two selects that you have

SELECT * 
FROM
   (SELECT 1) as s1 inner join
   (SELECT 2) as s2 on s1.id_pedido = s1.fk_id_pedido
SELECT *
FROM
    (SELECT 
        fk_id_produto,
        fk_id_pedido, 
        descricao_produto, 
        valor_produto 
    FROM 
        Pedido_Produto 
        INNER JOIN Produto 
            ON pedido_produto.fk_id_produto = produto.id_produto
     ) as s1 
INNER JOIN 
    (SELECT 
        id_cliente,
        nome_cliente,
        id_pedido,
        valor_pedido,
        data_do_pedido A
    FROM 
        Cliente 
        INNER JOIN  Pedido
            ON cliente.id_cliente = pedido.fk_id_cliente
    ) as s2 
    ON s1.id_pedido = s1.fk_id_pedido

BR

Solution 2:[2]

So you have four tables:

  • Products (P)
  • Clients (C)
  • Orders (O)
  • OrderProducts (OP)
SELECT
           *
FROM
           OP
  JOIN
           P ON P.ID = OP.P_ID
  JOIN
           O ON O.ID = OP.O_ID
  JOIN
           C ON C.ID = O.C_ID

That will produce one row for each OP and give you the product, order and client details

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joel Coehoorn
Solution 2 Aaron Reese