Search code examples
sqlmariadbsyntax-errorinner-join

SQL Syntax errors with multiple joins


I was writing a client in C to manage a library information system. I wrote this sql query in the client, but I have this syntax error. Can someone help me to find this error? thanks.

ERROR --> Error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as CD inner join COPIA as C on (CD.COPIA_idCOPIA = C.idCOPIA) inner join LIBRO a' at line 1

CODE:

  snprintf(q, 1024, "SELECT CD.COPIA_idCOPIA, CD.Ripiano, CD.Scaffale 
                     FROM COPIA DISPONIBILE as CD 
                            inner join COPIA as C on (CD.COPIA_idCOPIA = C.idCOPIA) 
                            inner join LIBRO as L on (C.LIBRO_idLIBRO = L.idLIBRO) 
                            inner join POSSEDERE as P on (C.idCOPIA = P.COPIA_idCOPIA) 
            WHERE P.BIBLIOTECA_idBIBLIOTECA = '%d' and L.Nome = '%s'", idBiblioteca, buffer);
        
  if(mysql_query(conn, q)!= 0) {
       print_error (conn, "query SELECT statement failed");
  } else {
       printf ("query SELECT statement succeeded: %lu rows affected(unsignedlong)mysql_affected_rows   (conn));
  }

Solution

  • If your table is really called COPIA DISPONIBILE with a space in it, you'll have to escape it by surrounding it with backticks:

    snprintf(q, 1024, "SELECT CD.COPIA_idCOPIA, CD.Ripiano, CD.Scaffale 
                         FROM `COPIA DISPONIBILE` as CD 
                                inner join COPIA as C on (CD.COPIA_idCOPIA = C.idCOPIA) 
                                inner join LIBRO as L on (C.LIBRO_idLIBRO = L.idLIBRO) 
                                inner join POSSEDERE as P on (C.idCOPIA = P.COPIA_idCOPIA) 
                WHERE P.BIBLIOTECA_idBIBLIOTECA = '%d' and L.Nome = '%s'", idBiblioteca, buffer);