I encounter a j2ee project that is a system that can dynamically construct SQL by user defined results and conditions. What I propose to do like: korzh's EasyQuery: DEMO
What's a user can do in this system is:
- config the result
- config the condition
- execute the auto-generated SQL
My question is: How to generate a sql statement that configured by user and these user selected result or condition fields may in different tables, I am confused that these tables maybe are related but also irrelated.
For example, as this picture shows,
- I selected Customer(table) -> [customer company name],[Order ID] (fields) as results.
- I selected Product(table) -> [Product ID = 1] as a condition.
the system will generate a SQL:
SELECT DISTINCT Customers.CompanyName AS "Customer Company name", Orders.OrderID AS "Order ID"
FROM (((Customers AS Customers
INNER JOIN Orders AS Orders ON (Customers.CustomerID = Orders.CustomerID ))
INNER JOIN Order_Details AS Order_Details ON (Orders.OrderID = Order_Details.OrderID ))
INNER JOIN Products AS Products ON (Products.ProductID = Order_Details.ProductID ))
WHERE
( Products.ProductID = 1 )
How the system finds out the inner relation between these tables, like:
(((Customers AS Customers
INNER JOIN Orders AS Orders ON (Customers.CustomerID = Orders.CustomerID ))
INNER JOIN Order_Details AS Order_Details ON (Orders.OrderID = Order_Details.OrderID ))
INNER JOIN Products AS Products ON (Products.ProductID = Order_Details.ProductID ))
In other words, I want to know how the "ad-hoc query" works to generate a feasible SQL statement through user's configuration. Is there any library of Java exists?
I would appreciate your help.