简体   繁体   中英

how to rewrite this query to make it work, mysql left join multiple from

The principal problem is in this question: here .

The important think is try to solve this:

THIS IS THE SIMPLE EXAMPLE QUERY PROBLEM

CREATE TABLE a ( id int );
CREATE TABLE b ( id int );
CREATE TABLE c ( id int );

SELECT id
, (SELECT MIN(b.id)
   FROM b LEFT JOIN c ON b.id = c.id 
       AND c.id = a.id
   WHERE b.id = a.id
  ) AS something
FROM a
;
The column 'a.id' in on clause is unknown (within LEFT JOIN)

Now, trying to solve the problem I wanted to try with this query:

select drf2.opcion 
from respuestas r2, opciones o2
left join detalle_respuesta_fija drf2 on o2.id_opcion = drf2.opcion and r2.id_respuesta
where o2.pregunta = 857
and r2.id_respuesta = 190968

 #1054 - La columna 'r2.id_respuesta' en on clause es desconocida

I need the query return this (example):

+--------
|Result
+--------
| id
| id
| NULL
| id
| NULL
+--------

.

Never use commas in the FROM clause. Always use proper, explicit, standard JOIN syntax.

In your case, that would be:

select drf2.opcion 
from respuestas r2 join
     opciones o2
     on r2.id_respuesta = o2.? left join  -- what column is used for the `JOIN`???
     detalle_respuesta_fija drf2
     on o2.id_opcion = drf2.opcion
where o2.pregunta = 857 and r2.id_respuesta = 190968;

If there is no join key between the first two tables, just use cross join :

select drf2.opcion 
from respuestas r2 cross join
     opciones o2 left join
     detalle_respuesta_fija drf2
     on o2.id_opcion = drf2.opcion and drf2.respuesta = r2.id_respuesta
where o2.pregunta = 857 and r2.id_respuesta = 190968

Instead of subquery you should join the a table and group by id

 SELECT a.id MIN(b.id)
 FROM b 
 INNER JOIN a ON a.id = b.id 
 LEFT JOIN c ON b.id = c.id 
     AND c.id = a.id
 GROUP BY a.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM