SQL+WHERE+别名+过滤的问题 Column 'code' in where clause is ambiguous

背景

有两张表,父表 task 和 子表 sub_task,它们使用id关联,并且都有自己的编号 code,但是在分页查询子任务列表时,编号需要使用父表编号+子表编号进行拼接(比如,task 表编号 为 zh001,sub_task表编号 为 01,则页面展示 为 zh001-01),并且需要根据组成的编号过滤。

问题

实际项目使用时,sql 往往很复杂,为了文章简洁明了、清晰,因此使用简化的sql说明问题

使用关联查询,并用组合的字段,起别名的方式过滤,报错提示:SQL 错误 [1052] [23000]: Column 'code' in where clause is ambiguous

select
	concat(ti.code, '-', sti.code) as code,
	sti.*,
	ti.name as task_name
from
	sub_task_info sti
left join task_info ti on
	ti.id = ti.task_id
where
	code like '%001%';

解决方案1

使用子查询,将第一次查询出来的结果,作为一个临时表,然后再做过滤。

select
    * 
from (
    select
	    concat(ti.code, '-', sti.code) as code,
    	sti.*,
    	ti.name as task_name
    from
    	sub_task_info sti
    left join task_info ti on
    	ti.id = ti.task_id
) temp
where
	code like '%001%';

解决方案2

还是使用原sql,只是在过滤时,不使用别名,而是用函数拼接。

select
	concat(ti.code, '-', sti.code) as code,
	sti.*,
	ti.name as task_name
from
	sub_task_info sti
left join task_info ti on
	ti.id = ti.task_id
where
	concat(ti.code, '-', sti.code) like '%001%';

参考链接:https://blog.csdn.net/helloworldchina/article/details/121218963

posted @ 2024-04-22 09:44  小小程序猿-DB  阅读(7)  评论(0编辑  收藏  举报