通过内连接或左/右连接替换标量子查询的比较

2022-01-23 00:00:00 join subquery mysql scalar-subquery

我需要使用内连接或右/左连接来编写此查询,但我不知道如何开始:

I need to write this query using inner joins or right/left joins but I don't know how to start:

select * from radicados where asignado = 
    (select estudianteid from estudiantes where usuario =
        (select usuarioid from usuarios where nombre =  $nombre_usuario))

但我不知道如何对连接做同样的事情.

But I don't know how to do the same with joins.

我想这一定是这样的:

select * from radicados inner join usuarios on usuarioid=usuario

推荐答案

看来你想要这样的东西:

It appears you want something like this:

select radicados.*
from
  radicados
  join estudiantes
    on radicados.asignado = estudiantes.estudianteid
  join usarios
    on estudiantes.usario = usarios.usarioid
  where usarios.nombre = $nombre_usuario

在构造这样的查询时,从 FROM 子句开始.根据它们之间的关系,将包含所需数据的各种表连接在一起.如果需要,添加一个 WHERE 子句,描述您想要过滤连接结果的任何其他条件.然后根据需要填写SELECT列表.

In constructing such a query, start with the FROM clause. Join together the various tables containing the needed data, based on the relationships between them. If needed, add a WHERE clause describing any additional conditions on which you want to filter the result of your join. Then fill in the SELECT list as appropriate.

在某些情况下,您可能还需要添加其他子句(ORDER BYGROUP BY 等),但是一旦您了解了基本查询,这还不错.

Under some circumstances you may need to add other clauses, too (ORDER BY, GROUP BY, etc.), but that's not bad once you understand basic queries.

相关文章