自联接mysql表

时间:2013-01-03 09:29:18

标签: mysql join

发薪日

  id   day    employee    income    expenses    tax
   1    7        3         600        100       30
   2    14       3         650        150       35
   3    14       2         680        200       38


SELECT p.income, p.tax, ps.expenses
FROM paydays p
LEFT JOIN paydays ps ON ps.day+7 = p.day
WHERE p.day = 14 AND p.employee = 3

这给了我想要的东西,650收入和35天的税收,第14天 第7天排100次开支

现在问题,

SELECT SUM(p.income), SUM(p.tax), SUM(ps.expenses)
FROM paydays p
LEFT JOIN paydays ps ON ps.day+7 = p.day
WHERE p.day = 14

应该给出

income = 1330  
tax = 73  
expenses = 100

但它将字段乘以2 income = 2660, tax = 146.....

2 个答案:

答案 0 :(得分:0)

SELECT 
    SUM(payday.income) as Income , 
    SUM(payday.tax) as Tax,  
    p.expenses as Expanses
FROM payday
LEFT JOIN payday as p ON p.id = payday.id - 1
WHERE day = 14

答案 1 :(得分:0)

也许我在你的解释中遗漏了一些东西,但你不能使用子查询来获得expenses,类似于:

SELECT SUM(p.income) TotalIncome, 
  SUM(p.tax) TotalTax, 
  ps.expenses Expenses
FROM paydays p
INNER JOIN
(
  select sum(expenses) expenses, day
  from paydays
  where day = 7
  group by day
) ps 
  ON ps.day+7 = p.day
WHERE p.day = 14
GROUP BY ps.expenses

请参阅SQL Fiddle with Demo

结果是:

| TOTALINCOME | TOTALTAX | EXPENSES |
-------------------------------------
|        1330 |       73 |      100 |