1

I want to using HQL with inner Join. But, a query syntax exception is thrown.

This is my C# code:

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);
}
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
Geda
  • 23
  • 5
  • 3
    Can you paste the shown exception? – wmk May 30 '15 at 14:16
  • Not sure if it's the problem, but you can at least try change the alias: "Select fq FROM Answers as a INNER ..." if fq is a column, or "Select * FROM Answers as fq INNER ..." if you want things from "fq". You just can't "select" a table. – Tim3880 May 31 '15 at 04:24

1 Answers1

0

The point here is

  • CROSS JOIN if there are no mapped relations,
  • JOIN on existing (mapped) relations.

So, in case, there is no mapped relation Question to Answer - we still can query it like this:

// 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";

In case we have mapping Answer.Question and IList<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";

Check the

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Unfortunately study. error is "Query Syntax Exception " the fact that I want to do; Table 1= Questions(questionId,question), Table2=Answers(answerId,questionId,answer) Sql Query="select q.question,a.answer from Questions as q inner join Answers as a on q.questionId=a.questionId" – Geda Jun 01 '15 at 07:52
  • Have you tried what I've shown to you? Mostly the Cross join with WHERE? try to follow my answer, and links.. and believe or not, that should give you results you need... – Radim Köhler Jun 01 '15 at 08:45
  • Seems you make it at the end... That's really really great! ;) Enjoy mighty NHibernate, sir – Radim Köhler Jun 01 '15 at 11:10