union not working empty results - mysql

I tried using inner join and union not working
sql="SELECT * FROM " +
"(SELECT order_id, order_date, order_status, order_value, order_sapId, order_from, order_clientAcct, order_error, order_visitId, order_cancelled, distributor_name " +
" FROM `orders` " +
" JOIN visits on visit_id = order_visitId " +
" JOIN Name ON user_id = visit_userId " +
" JOIN distributor ON distributor_id = visit_outlet_id " +
" WHERE order_from = 'CSFA' AND user_id = '"+ App.getUserData("user_id")+"' " +
")" +
" JOIN " +
"(SELECT order_id, order_date, order_status, order_value, order_sapId, order_from, order_clientAcct, order_error, order_visitId, order_cancelled, distributor_name " +
" FROM `orders` " +
" JOIN distributor ON order_clientAcct = distributor_accountName " +
" JOIN user ON salesEmpNo = user_sapId " +
" WHERE order_from = 'u' AND user_id = '"+ App.getUserData("user_id")+"' " +
") " +
"" +
"ORDER BY order_id DESC LIMIT 100" +
"";
I need a way to join the two results
1. tried inner join
2.tried union
E/SQLiteLog: (1) near "(": syntax error
11-24 19:53:01.017 13531-13531/E/AndroidRuntime: FATAL EXCEPTION: main
Process: , PID: 13531
android.database.sqlite.SQLiteException: near "(": syntax error (code 1): , while compiling: SELECT * FROM (SELECT order_id, order_date, order_status, order_value, order_sapId, order_from, order_clientAcct, order_error, order_visitId, order_cancelled, distributor_name FROM orders JOIN visits on visit_id = order_visitId JOIN Name ON user_id = visit_userId JOIN distributor ON distributor_id = visit_outlet_id WHERE order_from = 'CSFA' AND user_id = '75' ) UNION (SELECT order_id, order_date, order_status, order_value, order_sapId, order_from, order_clientAcct, order_error, order_visitId, order_cancelled, distributor_name FROM orders JOIN distributor ON order_clientAcct = distributor_accountName JOIN user ON salesEmpNo = user_sapId WHERE order_from = 'u' AND user_id = '75' ) ORDER BY order_id DESC LIMIT 100
That is the error log

after days of research finally got an answer .Used LEFT JOIN and OR to get data from table only where they match.
sql="" +
"SELECT DISTINCT order_id, order_date, order_status, order_value, order_sapId, order_from, order_clientAcct, order_error, order_visitId, order_cancelled, distributor_name " +
" FROM `orders` " +
" LEFT JOIN visits,user,distributor ON (visit_id = order_visitId AND user_id = visit_userId AND distributor_id = visit_outlet_id AND order_from = 'CSFA' AND user_id = '"+ App.getUserData("user_id")+"') OR " +
" " +
" ( order_clientAcct = distributor_accountName AND salesEmpNo = user_sapId AND order_from = 'SAP' AND user_id = '"+ App.getUserData("user_id")+"' )" +
" " +
"ORDER BY order_id DESC LIMIT 100" +
"";

Related

Convert mysql query to jpa query with pagination supported

I have mysql query for joining 3 tables, how can i convert this into JPA with pagination supported.
query :
SELECT promotion.name,
promotion.promotion_type,
promotion.start_date,
promotion.end_date,
promotion_history.`count` AS order_count,
Count(user_promotion_history.promotionid) AS user_count
FROM promotion
INNER JOIN user_promotion_history
ON promotion.promotionid = user_promotion_history.promotionid
INNER JOIN promotion_history
ON promotion.promotionid = promotion_history.promotionid
WHERE promotion.status = "created"
GROUP BY promotion.name,
promotion.promotionid,
promotion.promotion_type,
promotion.start_date,
promotion.end_date,
order_count;
I have created all entity and repository classes and used native query,
#Query(value = "select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date" +
" promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count" +
" from promotion" +
" inner JOIN user_promotion_history on" +
" promotion.promotionid = user_promotion_history.promotionid" +
" inner join promotion_history on" +
" promotion.promotionid = promotion_history.promotionid" +
" where promotion.status = :status" +
" group by" +
" promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count",
nativeQuery = true)
List<Object[]> findByStatus(#Param("status")PromotionStatus status);
but getting an error like this.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '.count as order_count, count(user_promotion_history.promotionid)
as user_count f' at line 1
For pagination i have used Pageable parameter.
#Query(value = "select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date," +
" promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count" +
" from promotion" +
" join user_promotion_history on" +
" promotion.promotionid = user_promotion_history.promotionid" +
" join promotion_history on" +
" promotion.promotionid = promotion_history.promotionid" +
" where promotion.status = ?1" +
" group by" +
" promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count \n-- #pageable\n",
nativeQuery = true)
List findByStatus(String status, Pageable pageable);
when i see query looks like this,
Hibernate: select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date, promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count from promotion join user_promotion_history on promotion.promotionid = user_promotion_history.promotionid join promotion_history on promotion.promotionid = promotion_history.promotionid where promotion.status = ? group by promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count
-- #pageable
order by join.user_count desc limit ?
error says : org.hibernate.engine.jdbc.spi.SqlExceptionHelper Unknown column 'join.user_count' in 'order clause'
somewhere "join." is getting added in order by clause.

Native JPA query and SQL query not giving the same result

I have 2 tables: one called issues and the other is time_entries which have id_issue as foreign key. I made an INNER JOIN based on the id_issue column.
SELECT
SUM(time_entries.hours)
, issues.id
, time_entries.created_on
, time_entries.updated_on
, issues.`estimated_hours`
, issues.`done_ratio`
FROM
issues
INNER JOIN
time_entries
ON
issues.id = time_entries.issue_id
WHERE
issues.project_id = 2
GROUP BY
issues.id
I put this query in a native query:
Query query = (Query) this.em.createNativeQuery(
"SELECT " +
" SUM(time_entries.hours) " +
" , issues.id " +
" , issues.estimated_hours" +
" , issues.done_ratio" +
"FROM " +
" issues " +
"INNER JOIN " +
" time_entries " +
"ON " +
" issues.id = time_entries.issue_id " +
"WHERE " +
" issues.project_id = 2 " +
"GROUP BY " +
" issues.id");
List<?> result = query.getResultList();
When i execute those 2 lines of Java code, I don't get the same result as executing this query in MySQL console but I got the same query in the trace.

syntax error (missing operator) in query expression sri.invoiceNo = sri.invoiceNo INNER JOIN Staff s oN s.Staffid = sr.userld

"SELECT SalesReturnId, ReturnDate, sr.InvoiceNo, (lastname & ', ' & firstname & ', ' & MI) as StaffName, TotalAmount, SUM(sri.Quantity) as TotalQuantity FROM SalesReturn sr INNER JOIN SalesReturnItem sri ON sr.InvoiceNo = sri.InvoiceNo INNER JOIN Staff s ON s.StaffId = sr.userID WHERE ReturnDate BETWEEN '" + startDate.ToString("yyyy-MM-dd") + "' AND '" + endDate.ToString("yyyy-MM-dd") + "' AND sr.InvoiceNo LIKE '%" + txtName.Text + "%' GROUP BY sr.InvoiceNo ORDER BY ReturnDate, sr.InvoiceNo DESC";
When I run that query I keep getting this error:
syntax error (missing operator) in query expression sri.invoiceNo =
sri.invoiceNo INNER JOIN Staff s oN s.Staffid = sr.userld
In Access you need parentheses when you have more than one join:
SELECT SalesReturnId, ReturnDate, sr.InvoiceNo,
(lastname & ', ' & firstname & ', ' & MI) as StaffName,
TotalAmount, SUM(sri.Quantity) as TotalQuantity
FROM (SalesReturn sr
INNER JOIN SalesReturnItem sri ON sr.InvoiceNo = sri.InvoiceNo )
INNER JOIN Staff s ON s.StaffId = sr.userID
WHERE ReturnDate BETWEEN '" + startDate.ToString("yyyy-MM-dd") + "' AND '" + endDate.ToString("yyyy-MM-dd") + "'
AND sr.InvoiceNo LIKE '%" + txtName.Text + "%'
GROUP BY sr.InvoiceNo
ORDER BY ReturnDate, sr.InvoiceNo DESC;

MySQL Query works in phpmyadmin but not in node

I have a query with LEFT joins which works fine in phpmyadmin but same query returns null for certain rows in node server. I am new to both node and MySQL.
Here is my query to fetch highest selling category between a date range:
SELECT o.order_id,c.category_id,c.category_name as Name, o.book_id, o.date_of_purchase, SUM(o.quantity) as Total, o.payment_method
FROM `order_details` as o
LEFT JOIN book as b on b.book_id = o.book_id
LEFT JOIN category as c on c.category_id = b.book_id
GROUP BY c.category_id
ORDER BY Total DESC LIMIT 1
Am i doing something wrong here?
Here are my table and query result:
Result of the same in node is :
{
"data": [
{
"order_id": 20,
"category_id": null,
"Name": null,
"book_id": 6,
"date_of_purchase": "2017-07-23T13:22:37.000Z",
"Total": 55,
"payment_method": "NB"
}
],
"status": 1,
"message": "Success"
}
Node code where I call the query:
/* Get highest selling category */
category.getHighestSelling = function(fromDate, toDate) {
var query = "SELECT min(o.order_id) , c.category_id , c.category_name as Name , o.book_id , min(o.date_of_purchase) , SUM(o.quantity) as Total , min(o.payment_method) " +
"FROM `order_details` as o " +
"LEFT JOIN book as b on b.book_id = o.book_id " +
"LEFT JOIN category as c on c.category_id = b.book_id " +
"GROUP BY c.category_id , o.book_id " +
"ORDER BY Total DESC LIMIT 1 ";
if (fromDate && toDate) {
query += "WHERE `date_of_purchase` BETWEEN '" + dateFormat(fromDate, "yyyy-mm-dd , h:MM:ss ") + "' AND '" + (dateFormat(toDate, "yyyy-mm-dd , h:MM:ss ") || new Date()) + "'";
}
return utilities.executeQuery(query);
};

MySQL Sum() from derived column

I am joining product and cart table to calculate for the total price for each cart. Here is my sql statement:
String sql = "SELECT p.productID, p.productName, p.productPrice, c.quantity, p.productPrice * c.quantity as new_unit_price, SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " WHERE c.custName = '" + custName + "'";
I derived a column named new_unit_price by multiplying the quantity from cart table and product price from product table. Then I want to use the derived column which is new_unit_price to sum up the price of all item in the cart. I get the data from the column in database by:
double subItemTotal = rs.getDouble("new_unit_price");
double totalPrice = rs.getDouble("totalPrice");
My new_unit_price works. But unfortunately, my sum does not works. It's still 0. Does anybody know how can I sum up the value from derived column? Thanks in advance.
To use the SUM() function, you'll need to do a GROUP BY at the end of your statement.
This should get your overall cart total:
String sql = "SELECT c.custname "
+ ", SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " AND c.custName = '" + custName + "'"
+ " GROUP BY c.custname;"
Also, I changed the WHERE to an AND so it is evaluated earlier and should make the query faster.
If you want the new_unit_price and the cart total in the same query, you have to go back into the tables again to get that data. Something like this should work:
String sql = "SELECT p.productID, p.productName, p.productPrice, c.quantity "
+ ", p.productPrice * c.quantity as new_unit_price, total.totalPrice FROM "
+ "( "
+ "SELECT c.custname "
+ ", SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " AND c.custName = '" + custName + "'"
+ " GROUP BY c.custname"
+ ") AS total "
+ "INNER JOIN sm_cart c "
+ "ON total.custname=c.custname "
+ "INNER JOIN sm_product p "
+ "ON p.productID = c.productID "