当我在 MySQL 控制台中运行它时,我有以下 SQL 查询,它按预期返回一个结果:
SELECT DISTINCT a.* FROM account a
INNER JOIN contact c ON a.id = c.accountId WHERE a.accountName LIKE '%[email protected]%'
OR a.id IN (SELECT e.accountId FROM environment e WHERE e.externalId LIKE '%[email protected]%'
OR e.name LIKE '%[email protected]%')
OR c.email = '[email protected]'
我在应用程序代码中使用相同的查询,但返回零结果:
@Query(value = "SELECT DISTINCT a.* FROM account a INNER JOIN contact c ON a.id = c.accountId WHERE a.accountName LIKE %?1% OR a.id IN " +
"(SELECT e.accountId FROM environment e WHERE e.externalId LIKE %?1% OR e.name LIKE %?1%) " +
"OR c.email = ?1", nativeQuery = true)
List<Account> findAccountByKeyword(String keyword);
我看到生成了以下 SQL,这对我来说看起来不错:
select distinct account0_.id as id1_0_, account0_.createdBy as createdB2_0_, account0_.createdDate as createdD3_0_, account0_.lastUpdatedBy as lastUpda4_0_, account0_.updatedDate as updatedD5_0_, account0_.accountName as accountN6_0_, account0_.globalMessage as globalMe7_0_, account0_.isConsultingPartner as isConsul8_0_, account0_.isNonProfit as isNonPro9_0_, account0_.isSuspended as isSuspe10_0_, account0_.note as note11_0_, account0_.parentId as parentI12_0_, account0_.products as product13_0_, account0_.salesforceId as salesfo14_0_, account0_.type as type15_0_, account0_.typeShort as typeSho16_0_, account0_.usedProducts as usedPro17_0_
from account account0_ inner join contact contact1_ on (account0_.id=contact1_.accountId)
where account0_.accountName like ? or account0_.id in (select environmen2_.accountId from environment environmen2_ where environmen2_.externalId like ?
or environmen2_.name like ?)
or contact1_.email=?
你知道这里可能出了什么问题吗?我已经验证
keyword
的值是正确的,所以我完全不知道还能尝试什么。关于本机 SQL 和 Spring 中的查询之间不一致的其他问题都在讨论日期类型的问题,但我什至没有在这里使用日期或任何特定于方言的内容。
如果您需要更多信息,请告诉我,我将相应地编辑我的问题。
你们的疑问真的一样吗?就像 Mysql 中的 '%[email protected]%' 和本机 SQL 中的 LIKE %?1% 一样。我猜你在某个地方丢失了参数前后的%。
用
like %?1%
替换 like CONCAT('%', ?1, '%')
可能是解决方案
我看到你加入了“帐户”表和“环境”表。 猜猜一个账户记录有很多环境记录。
尝试重写您的查询以仅选择环境 ID,而不选择帐户 ID。 也许有帮助。