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