How to join 2 select in mysql

Asked

Viewed 7,919 times

4

I have 2 select which are basically identical, changing only 1 table. I’m trying to put the 2 together in a single select, but I’m not getting it.

Follows the select:

SELECT DISTINCT
            a.id,
            a.unidade,
            a.posicao,
            a.nome,
            a.peso
        FROM
            produtos a,
            produtos_pedidos b
        WHERE
            a.id = b.id_produto
            and b.id_pedido IN (1,2)
        ORDER BY a.nome

Select 2:

 SELECT DISTINCT
            a.id,
            a.unidade,
            a.posicao,
            a.nome,
            a.peso
        FROM
            produtos a,
            pedidos_barganha b
        WHERE
            a.id = b.id_produto
            and b.id_pedido IN (1,2)
        ORDER BY a.nome

Does anyone know how I can put the two together?

2 answers

6


You will have to use the operator UNION between them, in your case would be so:

SELECT DISTINCT
    a.id,
    a.unidade,
    a.posicao,
    a.nome,
    a.peso
FROM
    produtos a,
    produtos_pedidos b
WHERE
    a.id = b.id_produto
    and b.id_pedido IN (1,2)

UNION

SELECT DISTINCT
    p.id,
    p.unidade,
    p.posicao,
    p.nome,
    p.peso
FROM
    produtos p,
    pedidos_barganha pb
WHERE
    p.id = pb.id_produto
    and pb.id_pedido IN (1,2)
ORDER BY nome

It is worth noting that if you use the UNION the Order BY should be written only at the end of your entire query.

Beyond the UNION, you can also use the UNION ALL in that link you can see the difference between them and choose the one that will suit you best

  • Gave the following error #1250 - Table 'a' of one of the Selects cannot be used in field list

  • @Hugoborges edited the answer, you could test?

  • now this way #1250 - Table 'p' of one of the Selects cannot be used in field list

  • 1

    found the bug, just change the ' ORDER BY name'

  • @Hugoborges fix this and added one more information at the end

3

Uses the UNION.

SELECT DISTINCT
    a.id,
    a.unidade,
    a.posicao,
    a.nome,
    a.peso
FROM
    produtos a,
    produtos_pedidos b
WHERE
    a.id = b.id_produto
AND b.id_pedido IN (1, 2)
UNION
    SELECT DISTINCT
        c.id,
        c.unidade,
        c.posicao,
        c.nome,
        c.peso
    FROM
        produtos c,
        pedidos_barganha d
    WHERE
        c.id = d.id_produto
    AND d.id_pedido IN (1, 2)
    ORDER BY
        c.nome
  • Good in its form gave the following error, #1221 - Wrong use of UNION and ORDER BY

  • True. I took the order by of the first SELECT.

  • error changed to #1250 - Table 'a' of one of the Selects cannot be used in field list

Browser other questions tagged

You are not signed in. Login or sign up in order to post.