簡體   English   中英

如何重寫此查詢以使其工作,mysql left join multiple from

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

主要問題在於這個問題: here

重要的想法是嘗試解決這個問題:

這是一個簡單的示例查詢問題

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)

現在,嘗試解決我想嘗試使用此查詢的問題:

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

我需要查詢返回這個(示例):

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

.

切勿FROM子句中使用逗號。 始終使用正確、明確、標准的JOIN語法。

在你的情況下,那將是:

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;

如果前兩個表之間沒有join鍵,只需使用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

您應該加入一個表並按 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM