2014-08-27 31 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

相關問題