2015-05-30 122 views
1

我想使用內部連接的HQL。但是,引發了查詢語法異常。NHibernate HQL內部連接(SQL Server,Visual C#)

這是我的C#代碼:

string sqlQuery = "Select fq FROM Answers as fq INNER JOIN Questions as q " + 
    " on fq.questionId=q.questionId"; 

IList Result; 
int count = 0; 

try 
{ 
    using (ISession session = ConnectionModule.OpenSession()) 
    { 
     IQuery query = session.CreateQuery(sqlQuery); 
     session.CreateCriteria(typeof(Answers)); 
     Result = query.List(); 
    } 
} 
catch(Exception ex) 
{ 
    MessageBox.Show(ex.Message+"\n"+ex.InnerException); 
} 
+3

你可以粘貼顯示異常? – wmk

+0

不知道是否是問題,但您至少可以嘗試更改別名:「如果fq是列,或者」Select * FROM Answers as fq INNER ...「,則選擇fq FROM Answers作爲INNER ... if你想要「fq」的東西。你只是不能「選擇」一張桌子。 – Tim3880

回答

0

點這裏

  • CROSS JOIN如果沒有映射關係,
  • JOIN現有(映射)關係。

所以,在情況下,有沒有映射關係QuestionAnswer - 我們仍然可以查詢它是這樣的:

// instead of INNER JOIN we use 'comma' to produce CROSS JOIN 
// instead of ON we need WHERE 
// string sqlQuery = "Select fq FROM Answers as fq, INNER JOIN Questions as q "+ 
// "on fq.questionId=q.questionId"; 

string sqlQuery = "Select fq FROM Answers as fq, Questions as q " + 
    " WHERE fq.questionId=q.questionId"; 

在情況下,我們有映射Answer.QuestionIList<Answer> Question.Answers

// the Reference (C#) is the way how to express ON 
string sqlQuery = "Select fq FROM Answers as fq INNER JOIN fq.Questions as q"; 

檢查

+0

不幸的是研究。錯誤是「查詢語法異常」我想要做的事實;表1 =問題(questionId,問題),表2 =答案(answerId,questionId,答案)Sql Query =「select q.question,a.answer from qq內部聯接答案as a on q.questionId = a.questionId」 – Geda

+0

你有沒有試過我向你展示過的東西?大多數十字會加入WHERE?嘗試按照我的答案,並鏈接..並相信與否,這應該給你你需要的結果... –

+0

似乎你在最後...它真的很棒! ;)享受強大的NHibernate,先生 –