Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在Hibernate中实现多列选择子查询的最佳方法是什么?_Sql_Postgresql_Hibernate - Fatal编程技术网

Sql 在Hibernate中实现多列选择子查询的最佳方法是什么?

Sql 在Hibernate中实现多列选择子查询的最佳方法是什么?,sql,postgresql,hibernate,Sql,Postgresql,Hibernate,我想实现具有多列的子查询,以便使用CriteriaAPI进行分组。我知道使用CriteriaAPI是不可能的,而且我不能使用本机查询 有一个数据库架构示例: CREATE TABLE IF NOT EXISTS conversation ( id BIGSERIAL PRIMARY KEY ); CREATE TABLE IF NOT EXISTS participant ( id BIGSERIAL PRIMARY KEY, conversa

我想实现具有多列的子查询,以便使用CriteriaAPI进行分组。我知道使用CriteriaAPI是不可能的,而且我不能使用本机查询

有一个数据库架构示例:

CREATE TABLE IF NOT EXISTS conversation (
    id BIGSERIAL PRIMARY KEY
);

CREATE TABLE IF NOT EXISTS participant (
    id              BIGSERIAL PRIMARY KEY,
    conversation_id BIGINT REFERENCES conversation (id)
);

CREATE TABLE IF NOT EXISTS message (
    id              BIGSERIAL PRIMARY KEY,
    created_at      TIMESTAMP,
    conversation_id BIGINT REFERENCES conversation (id),
    sender_id       BIGINT REFERENCES participant (id),
    receiver_id     BIGINT REFERENCES participant (id)
);

INSERT INTO conversation (id) VALUES (1), (2), (3);
INSERT INTO participant (conversation_id) VALUES (1), (1), (1), (2), (2), (3), (3), (3), (3);
INSERT INTO message (conversation_id, sender_id, receiver_id) VALUES (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 3), (2, 4, 5), (2, 5, 4), (2, 5, 4), (3, 9, 6), (3, 9, 7), (3, 9, 8);
我想从每次对话中获取最后的消息。查询如下所示:

SELECT m.*
FROM message m
WHERE (m.conversation_id, m.created_at)
  IN (SELECT
        m.conversation_id,
        max(m.created_at)
      FROM message m
      GROUP BY m.conversation_id);
我找到的第一种方法是将两列连接起来。它不是很健壮:

SELECT m.*
FROM message m
WHERE concat(m.conversation_id, m.created_at)
  IN (SELECT concat(m.conversation_id,
                    max(m.created_at))
      FROM message m
      GROUP BY m.conversation_id);
第二种方法是查找每个组的最大值标识符。这会降低性能,并且在Criteria API的聚合函数中存在排序问题


有没有办法不用原生查询/HQL/JPQL就用可靠且快速的东西替换子查询?

你能在Hibernate中使用
行数
吗?@lad2025正如我所知,Criteria API不支持
行数
函数。