在尝试编写SQL查询以过滤出某些数据时遇到了一些问题。基本上我的表设计是1 ward can have many beds, and 1 bed can have many enrollments
。
我的ward table has w_id as PK
,bed table with b_id as PK and w_id as FK
,enrollment table with e_id as PK and b_id as FK
。
我现在想做的是获取床单以及病房详细信息,这些信息在登记表中不存在。我在Oracle数据库中尝试了SQL查询:
SELECT * FROM bed b
INNER JOIN ward w ON b.WARD_ID = w.ID
WHERE NOT EXISTS ( SELECT * FROM bed b2
INNER JOIN enroll e ON e.BED_ID = b2.ID
WHERE b2.ID = b.ID );
它确实设法给了我想要的结果。但是,当我尝试将上述查询作为本机查询放入Spring Boot中时,出现了错误消息:
Encountered a duplicated sql alias [ID] during auto-discovery of a native-sql query; nested exception is org.hibernate.loader.custom.NonUniqueDiscoveredSqlAliasException: Encountered a duplicated sql alias [ID] during auto-discovery of a native-sql query
有什么想法吗?谢谢!
答案 0 :(得分:0)
SELECT * FROM bed b
INNER JOIN ward w ON b.WARD_ID = w.ID
看来床和病房的桌子上都有名为id
的列。通过执行select *,可以隐式包含床和病房表中的所有列。因此,您将包括两个名为id
的列。 not exists
部分令人分心。某些sql客户端将允许这样做,但是休眠更为严格。我没有一个可以立即进行测试的环境,但是,如果这是问题的话,可以解决以下问题。
SELECT b.id, b.ward_id, w.ward_name FROM bed b
INNER JOIN ward w ON b.WARD_ID = w.ID
WHERE NOT EXISTS ( SELECT b2.id FROM bed b2
INNER JOIN enroll e ON e.BED_ID = b2.ID
WHERE b2.ID = b.ID );
答案 1 :(得分:0)
我不知道这是否与您的问题有关,但是您在子查询中不需要JOIN
。一个更简单的版本是:
SELECT *
FROM bed b INNER JOIN
ward w
ON b.WARD_ID = w.ID
WHERE NOT EXISTS (SELECT 1
FROM enroll e
WHERE e.BED_ID = b.ID
);