1

我正在使用 java java.sql.* 从 SQLite DB 进行查询。我发现了一个问题,我将 sqlString 编写为:

SELECT n.Name as Name, 
       c.Value as Value0, 
       d.Value as Value1 
FROM  (Table1 c inner join Table2 n on c.NameID = n.ID),
      Table3 d 
WHERE c.RunID = 1 
      and d.RunID = 2 
      and c.NameID = d.NameID

该语句stmt.executeQuery(sqlQuery)引发以下异常:

java.sql.SQLException: no such column: n.Name
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.executeQuery(Stmt.java:89).............

Name已经是 Table2 表的一部分。同样的语句在 SQLite 命令提示符下工作正常。但是当我删除左括号并尝试从java执行时,没有问题。知道为什么会这样吗?

4

3 回答 3

0

内部查询中使用的变量不能被外部引用。例如,您在内部 sql 中使用了变量 n。但是你在外面提到它。变量 n 超出了它的范围。

于 2012-07-04T12:03:50.867 回答
0

尝试这样的事情,使用子结果集

SELECT rs1.Name AS NAME, 
       rs1.Value0 AS Value0, 
       d.Value AS Value1 
FROM  (SELECT n.Name AS NAME, 
       c.Value AS Value0, 
       d.Value AS Value1 
       FROM Table1 c INNER JOIN Table2 n ON c.NameID = n.ID) rs1,
      Table3 d 
WHERE c.RunID = 1 
      AND d.RunID = 2 
      AND c.NameID = d.NameID
于 2012-07-04T12:06:56.437 回答
0

嗨朋友感谢您的快速回复。我能够解决这个问题。我正在分享这个,所以如果任何其他人遇到这个问题可以这样做:

SELECT ABC.Name as Name, ABC.Value as Value0, d.Value as Value1
  FROM
  (select n.Name as Name, c.Value as Value0 from Table1 c
   inner join Table2 n on c.NameID = n.ID) AS ABC,
Table3 d ......;

问候,托

于 2012-07-04T12:10:37.003 回答