数据库查询问题求大神解答

select unitcode from g3_unit where unitname like'%部门001%'这个可以查询出来

select unitno from g3_unit where unitcode like '1___'这个也可以查询出来

select unitno from g3_unit where unitcode like '(select unitcode from g3_unit where unitname like'%部门001%')___' 这两个加起来就不行了,我知道肯定是我写法的问题,请问各位大神怎么改一下?

select unitno from g3_unit where unitcode like '(select unitcode from g3_unit where unitname like'%部门001%')___'

这句sql中子查询 用使用了 单引号 '' 这个是有问题的,会当成 字符串处理。但同时 内部有还有一组单引号 '%部门001%' 这回导致sql语句语法错误。
第二个问题是 子查询查询出来可能有多个 结果,不能作为like的条件。如果查询出来的结果大于1个 会提示:[Err] 1242 - Subquery returns more than 1 row

第三个问题是 你这里想实现 字符串的拼接,建议使用concat函数进行拼接。

你可以使用 多表查询的方式来实现你要的效果:

SELECT
g3_unit.unitno
FROM
g3_unit,
(
SELECT
unitcode
FROM
g3_unit
WHERE
unitname LIKE '%部门001%'
) tempTab
WHERE
g3_unit.unitcode LIKE CONCAT(tempTab.unitcode, "_")

你第三个根本没有变成li ke得语法,所有匹配的不对。

SELECT
g3_unit.unitno
FROM
g3_unit,
(
SELECT
unitcode
FROM
g3_unit
WHERE
unitname LIKE '%部门001%'
) tempTab
WHERE
g3_unit.unitcode LIKE CONCAT(tempTab.unitcode, "_")

SQL中''是当作字符串处理的