我有这段代码并且不断出现语法错误。
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)
我在这里缺少什么或者如何加入三张桌子。
答案 0 :(得分: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";
答案 1 :(得分: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