9

TICKETS表中的字段:

ID TICKETID CUSTOMER
234   29      9798797
235   76      7887878

RECEPTS中的字段:

ID   DATENEW    TOTAL
234 2012-12-03   22.57
235 2012-12-03   33.98

PAYMENTS中的字段:

RECEIPT   PAYMENT
234       cash
235       debt

CUSTOMERS中的字段:

ID            NAME
9798797       John
7887878       Helen

表之间的关系很容易理解:TICKETS.CUSTOMER=CUSTOMERS.ID; PAYMENTS.RECEIPT=RECEIPTS.ID=TICKETS.ID

我希望达到的最终结果:

TICKETID DATENEW      NAME    PAYMENT TOTAL
29       2012-12-03   John     cash   22.57
76       2012-12-03   Helen    debt   33.98

我试图做这样的事情,但它在某处出错:

Select TICKETS.TICKETID, RECEIPTS.DATENEW, PAYMENTS.TOTAL,  CUSTOMERS.NAME, PAYMENTS.PAYMENT FROM PEOPLE, RECEIPTS 
INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
ORDER BY RECEIPTS.DATENEW
4

2 回答 2

11

您应该能够使用以下内容来获得结果:

select t.ticketid,
  date_format(r.datenew, '%Y-%m-%d') datenew,
  c.name,
  p.payment,
  r.total
from tickets t
left join RECEPTS r
  on t.id = r.id
left join CUSTOMERS c
  on t.customer = c.id
left join payments p 
  on t.id = p.RECEIPT
  and r.id = p.RECEIPT

请参阅带有演示的 SQL Fiddle

结果:

| TICKETID |    DATENEW |  NAME | PAYMENT | TOTAL |
---------------------------------------------------
|       29 | 2012-12-03 |  John |    cash | 22.57 |
|       76 | 2012-12-03 | Helen |    debt | 33.98 |
于 2012-12-03T14:05:57.683 回答
6

这将给出您想要的输出:

SELECT
    p.RECEIPT AS TICKETID,
    r.DATENEW,
    c.NAME,
    p.PAYMENT,
    r.TOTAL
FROM
    PAYMENTS p
LEFT JOIN
    RECEIPTS r ON r.ID = p.RECEIPT
LEFT JOIN
    TICKETS t ON t.ID = p.RECEIPT
LEFT JOIN
    CUSTOMERS c ON c.ID = t.CUSTOMER
ORDER BY
    r.DATENEW DESC
于 2012-12-03T14:05:00.007 回答