2

我有这段代码并且不断收到语法错误。

query = "SELECT * "+
"FROM Product " +
"INNER JOIN Orders ON (Product.ItemID=Orders.ItemID) " +
"LEFT OUTER JOIN SupplierProduct ON (Orders.ItemID=SupplierProduct.ItemID) "+
"WHERE Product.Receiver = 'Fred' " +
"ORDER BY Product.ItemName";    

DefaultTableModel data = table.getQuery(query);

我也尝试过INNER JOIN代替LEFT OUTER JOIN. 我不断尝试的错误是。

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing     operator) in query expression '(Product.ItemID=Orders.ItemID) LEFT OUTER JOIN  SupplierProduct ON (Orders.ItemID=SupplierProduct.ItemID'.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)

我在这里缺少什么或如何加入三个表。

4

2 回答 2

2

尝试使用这样的括号:

query = "SELECT * "+
        "FROM (Product " +
        "INNER JOIN Orders ON (Product.ItemID=Orders.ItemID)) " +
        "LEFT OUTER JOIN SupplierProduct ON (Orders.ItemID=SupplierProduct.ItemID) "+
        "WHERE Product.Reciever = 'Fred' " +
        "ORDER BY Product.ItemName";  
于 2013-08-08T13:41:48.397 回答
0

看起来 JDBC 可能难以解析连接的顺序。这可能是您正在与之交互的数据库引擎特有的问题,但无论如何,如果您使用括号指定连接操作的顺序,任何引擎都应该能够正确解析查询:

query = "SELECT * "+
"FROM (Product " +
"INNER JOIN Orders ON (Product.ItemID=Orders.ItemID)) " +
"LEFT OUTER JOIN SupplierProduct ON (Orders.ItemID=SupplierProduct.ItemID) "+
"WHERE Product.Reciever = 'Fred' " +
"ORDER BY Product.ItemName";    

DefaultTableModel data = table.getQuery(query);

更多细节:

基本上,这个想法是分离每个连接,以便它可以或多或少地解释为一个独立的表。这有助于更完整地区分

SELECT * 
FROM (Table1 JOIN Table2 ON Table1.a = Table2.a) 
     JOIN Table3 on Table3.b = Table2.b

SELECT * 
FROM Table1 
     JOIN (Table2 JOIN Table3 on Table3.b = Table2.b) ON Table1.a = Table2.a

另外,请注意,您可能需要为第一次连接的结果设置别名,如下所示:

SELECT * 
FROM (Table1 JOIN Table2 ON Table1.a = Table2.a) as join1 
     JOIN Table3 on Table3.b = join1.b
于 2013-08-08T13:42:27.780 回答