Home > Back-end >  use multiple join in a single query
use multiple join in a single query

Time:12-17

I'm trying to modify a previous query to remove the where parts and use join, but I get an error when I do it. I've tried to read the Oracle doc but I didn't find anything to fix my error.

Previous query :

SELECT DISTINCT 
    CLI.IDCLI, CLI.NOMCLI,CLI.PRENOMCLI
FROM
    LIVRAISON LIV, LIVRAISON LIV1, CLIENT CLI, COMMANDE COM, CLIENT CLI1, COMMANDE COM1
WHERE 
    CLI.IDCLI = COM.IDCLI
    AND COM.IDCOM = LIV.IDCOM
    AND CLI1.IDCLI = COM1.IDCLI
    AND COM1.IDCOM = LIV1.IDCOM
    AND LIV.DATELIV = LIV1.DATELIV
    AND LIV.IDLIV = LIV1.IDLIV
    AND CLI1.NOMCLI = 'MARTIN'
    AND CLI.IDCLI != CLI1.IDCLI
ORDER BY 
    CLI.IDCLI ASC;

New query & error:

SQL> SELECT DISTINCT CLI.IDCLI, CLI.NOMCLI,CLI.PRENOMCLI
  2  FROM LIVRAISON LIV      NATURAL JOIN LIVRAISON LIV1
  3                          INNER JOIN COMMANDE COM       ON COM.IDCOM=LIV.IDCOM,
  4        LIV1              INNER JOIN COMMANDE COM1      ON LIV1.IDCOM=COM1.IDCOM,
  5        CLIENT CLI        INNER JOIN COM                ON CLI.IDCLI=COM.IDCOM,
  6        COM1              INNER JOIN CLIENT CLI1        ON CLI1.IDCLI=COM1.IDCLI
  7  WHERE CLI1.NOMCLI='MARTIN'
  8  AND CLI.IDCLI!= CLI1.IDCLI
  9  ORDER BY CLI.IDCLI ASC;
      COM1              INNER JOIN CLIENT CLI1        ON CLI1.IDCLI=COM1.IDCLI
      *
ERROR at line 6:
ORA-00942: table or view does not exist

CodePudding user response:

Avoid NATURAL JOIN, unless you're a seasoned expert at join magic.

Don't mix old comma syntax with join syntax.

Use unique table aliases.

SELECT DISTINCT
  CLI.IDCLI, 
  CLI.NOMCLI, 
  CLI.PRENOMCLI
FROM LIVRAISON LIV
JOIN LIVRAISON LIV2 ON LIV2.DATELIV = LIV.DATELIV
                   AND LIV2.IDLIV   = LIV.IDLIV
JOIN COMMANDE  COM  ON COM.IDCOM    = LIV.IDCOM
JOIN CLIENT    CLI  ON CLI.IDCLI    = COM.IDCLI
JOIN COMMANDE  COM2 ON COM2.IDCOM   = LIV2.IDCOM
JOIN CLIENT    CLI2 ON CLI2.IDCLI   = COM2.IDCLI
WHERE CLI2.NOMCLI = 'MARTIN'
  AND CLI.IDCLI  != CLI2.IDCLI
ORDER BY 
  CLI.IDCLI ASC;
  • Related