【问题标题】:How to create right outerjoin in MySQL如何在 MySQL 中创建右外连接
【发布时间】:2012-06-08 17:34:08
【问题描述】:

我正在使用 JPA、Hibernate、MySQL。

我有两个表 Upload,UploadRating。每个上传可以在 UploadRating 表中具有多个评级,即 OneToMany。 UploadRating 有一个属性 user ,它定义了对上传进行评分的用户。

现在我想知道所有没有为用户提供 UploadRating 的上传。 所以查询类似于:

from Upload up,  UploadRating  ur where ur.upload=up and ur.user != :usrId 

我知道上述查询存在缺陷。在这种情况下,我们需要使用外连接。谁能帮我查询一下。

【问题讨论】:

    标签: mysql sql hibernate jpa


    【解决方案1】:

    在 SQL 中你可以使用:

    select 
      * 
    from 
      Upload up 
    where 
      not exists (select * from UploadRating ur where ur.upload_id=up.id and ur.user = :usrId)
    

    假设upload_id 是包含每个上传的唯一ID 的上传评级列。

    使用连接的等效 SQL 是这样的:

    select 
      * 
    from 
      Upload up 
      left outer join UploadRating ur on ur.upload_id=up.id
    where 
      (ur.user <> :usrId) or (ur.user is null)
    

    【讨论】:

    • 如果我正在尝试这个,我得到以下异常:org.hibernate.hql.internal.ast.QuerySyntaxException:意外令牌:在第 1 行附近,第 72 列 [来自 com.kids.domain.Upload as up left outer join UploadRating as ur on ur.upload_id=up.id where ur.subCont=:subCont and ur.user != :usrId and modified=true and semiFinalUpload = :semiFinalUp order by :orderBy]
    • 不知道 - on 是正确的 SQL,我不知道为什么 Hibernate 不喜欢它(还要注意我修复了 where 条件中的错误)
    • 我也在尝试您的第一个选项“不存在”。但它返回所有行。两个表中的共同列是上传;即 UploadRating.uploadId = Upload.id
    • ...刚刚意识到:您要的是 HQL 查询,而不是 SQL 查询 - 对吗?
    • 是的,我想使用 HQL,因为这会给我直接上传的对象。如果我使用本机 SQL;它将返回两个表的列,并且仅创建上传对象可能会变得混乱
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2015-06-05
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多