mysql - 按存在子查询中的字段对 MySql 查询进行排序

标签 mysql sql

我正在寻找一种方法,可以按“哪里存在”查询中存在的字段对查询进行排序。
尝试使用存在子查询中的字段时出现“未知列”错误。
示例查询;

select
    *
from
    `table_a`
where
    `a_field` = 'foo'
    and exists (
            select
                *
            from
                `table_b`
            where
                `table_a`.`an_id` = `table_b`.`another_id` and `table_b`.`another_field` = 'bar'
        )
order by
    `table_a`.`created_at` asc,
    `table_b`.`another_id` desc;

是使用内部联接查询的唯一解决方案,例如;

select
    `t1`.*
from
    `table_a` as `t1`
    inner join `table_2` as `t2` on `t2`.`another_id` = `t1`.`an_id`
where
    `t1`.`a_field` = 'foo'
    and `t2`.`another_field` = 'bar'
order by
    `t1`.`created_at` asc,
    `t2`.`another_id` desc;

最佳答案

您的示例查询是按 another_id 排序的,该 ID 在相关子句中使用。所以,你可以这样做:

select a.*
from table_a a
where a.a_field = 'foo' and
      exists (select 1
              from table_b b
              where a.an_id = b.another_id and
                    b.another_field = 'bar'
             )
order by a.created_at asc,
         a.an_id desc;

假设您确实想要一个不同的列,您可以使用JOIN。问题是可能有不止一行匹配。因此,您需要删除子查询中的重复项:

select a.*
from table_a a join
     (select b.another_id, max(b.another_col) as another_col
      from table_b b
      where another_field = 'bar'
      group by b.another_id
     ) b
     on a.an_id = b.another_id
where a.a_field = 'foo'
order by a.created_at asc, b.another_id desc;

如果您知道最多一行会匹配,则只能使用您的 JOIN 形式。

关于mysql - 按存在子查询中的字段对 MySql 查询进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56422738/

相关文章:

sql - 临时数据和存储库模式

sql - 向 UTL_MAIL.SEND 提供凭据以绕过 ORA-29278

mysql - Codeigniter 在 View 之前转换数据

mysql - 是否可以使此 SQL 查询运行得更快?

mysql - mysql 在将成功返回给客户端之前是否将请求的修改写入文件系统

mysql - 日期范围每行动态变化

MySQL select语句没有使用索引

sql - 批量插入时跳过错误

c# - 有没有支持C++和C#的ORM(Object Relational Mapper)框架

php - While 循环和 mysql_fetch_assoc 在一个查询上?