我如何从两个表中减去

时间:2016-05-03 10:56:37

标签: php mysql

我想从收入总表中减去总费用,但每当我运行查询时,我都会得到一个错误的数字。

package pack;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



public class FileUploadHandler extends HttpServlet {
    private final String UPLOAD_DIRECTORY = "D:/Data Repository.txt";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //process only if its multipart content
        if(ServletFileUpload.isMultipartContent(request)){
            try {
                List<FileItem> multiparts = new ServletFileUpload(
                                         new DiskFileItemFactory()).parseRequest(request);

                for(FileItem item : multiparts){
                    if(!item.isFormField()){

                        item.write(new File(UPLOAD_DIRECTORY));


                    }
                }

               //File uploaded successfully
               request.setAttribute("message", "File Uploaded Successfully");
            } catch (Exception ex)
            {
               request.setAttribute("message", "File Upload Failed due to " + ex);
            }          

        }else{
            request.setAttribute("message",
                                 "Sorry this Servlet only handles file upload request");
        }

    request.getRequestDispatcher("/result.jsp").forward(request, response);
    } 
}

收入表总共有40000,而费用表总共有5000,因此查询得到30000。

1 个答案:

答案 0 :(得分:0)

您正在进行加入,您应该进行子查询。试试这个:

SELECT Source, in_Amount, out_Amount, total_income - total_expenses FROM
(
  SELECT income.Source, SUM(income.Amount) as in_Amount,   SUM(expenses.Amount) as out_Amount,
  ( SELECT SUM(income.Amount) ) AS total_income,
  ( SELECT SUM(expenses.Amount) ) AS total_expenses
  FROM income as income, expenses
) t