2014-08-27 49 views
0

尝试将JOIN语句用于从多个表中选择值时,我得到ORA-00932: inconsistent datatypes: expected - got BLOB。以下是我的Oracle SQL代码:ORA-00932:不一致的数据类型:预计 - 在尝试连接不同的表时遇到BLOB

SELECT 
    MAX(questions.id), 
    MAX(questions.question), 
    MAX(questions.author), 
    MAX(questions.datetime), 
    MAX(answers.answer), 
    MAX(answers.usr), 
    MAX(answers.ansdatetime) 
FROM 
    questions 
LEFT JOIN 
    answers ON 
     questions.id = answers.question 
LEFT JOIN 
    questions_tags ON 
     questions.id = questions_tags.question_id 
WHERE 
    questions_tags.tag_id IN (1,2,3,4,5,6) 
GROUP BY 
    questions.id, answers.id 
ORDER BY 
    questions.datetime DESC 

以下是三个表的表结构:

questions

id int not null, 
question varchar(999), 
details varchar(1000) not null, 
author int not null, 
datetime varchar(999) 

answers

id int not null, primary key(id), 
question int not null, 
answer blob not null, 
usr int not null, 
ansdatetime int not null 

questions_tags

id INT NOT NULL, 
question_id INT NOT NULL, 
tag_id INT NOT NULL, 
PRIMARY KEY(id) 

这里有什么问题?

+0

我的猜测是MAX未定义为BLOB值,所以'MAX(answers.answer)'失败。您可能实际上需要一个子查询,而不是单独采用每列的MAX。或者将所有选定的列放在GROUP BY中,而不仅仅是ID。 – IMSoP 2014-08-27 23:05:10

+0

'answers.answer'是一个'blob'。你不能在'blob'上做'MAX'。但是你似乎不太可能想在每个列上做一个'MAX'。这通常会将数据组合在一起用于多行。你真的想为特定问题得到最近的答案吗? – 2014-08-27 23:05:46

+0

@JustinCave是的,如果答案存在,我需要得到最近回答的问题的答案。 – DemCodeLines 2014-08-27 23:18:53

回答

3

正如评论所说,这不起作用,因为您不能在blob列上执行max列。然而,你可以重写这个查询,以不使用聚合:

with a as (
    select 
     *, -- might need to enumerate columns 
     row_number() over (partition by question order by ansdatetime desc) as rn 
    from 
     answers 
) 
select 
    q.id, 
    q.question, 
    q.author, 
    q.datetime, 
    a.answer, 
    a.usr, 
    a.ansdatetime 
from 
    questions q 
     left join 
    a 
     on q.id = a.question and rn = 1 -- assuming you're only looking for latest answer per q 
where 
    exists (
     select 
      'x' 
     from 
      questions_tags t 
     where 
      q.id = t.question_id and 
      t.tag_id in (1,2,3,4,5,6) 
    ) 
order by 
    q.datetime desc 
+0

嘎。我写了他在这个问题上发布的怪物,更多的是一个笑话而不是一个严肃的建议。在MySQL中,引擎只是为这些列取第一行,您可以在select中包含不在分组中的列。我根据我所知道的(MySQL)计算出了最初的查询,然后当它在Oracle中不起作用时,开玩笑地建议MAX。现在,看到你必须做的复杂的废话......我现在实际上喜欢关于MySQL的一些东西。呵呵。 +1的答案,如果可以的话,我会让它有+2的耐心与甲骨文打交道。 – 2014-08-28 01:50:30

+1

@Chris实际上,MySQL并不会为这些列取第一行,它需要在每个组中选择任意一行*:[“服务器可以自由选择每个组中的任何值,除非它们相同,所选的值是不确定的。“](http://dev.mysql.com/doc/refman/5.7/en/group-by-extensions.html)。在PostgreSQL中(也可能是Oracle,我不知道),你可以定义一个FIRST()聚合函数并使用一个嵌入的ORDER BY('SELECT FIRST(x ORDER BY y)...'), *保证每个组的第一个。这是MySQL在健壮性之前提供便利的一个很好的例子。 – IMSoP 2014-08-28 09:10:48

+0

@IMSoP够公平的。至于这是不是一件坏事......呃。你仍然可以在MySQL中使用集合函数(或者启用“FULL GROUP BY”),所以如果它关系到列的来源,你可以指定。在我看来,MySQL在这两方面都是最好的。 – 2014-08-28 12:27:47

相关问题