复杂的SQL代码

时间:2014-10-03 17:20:57

标签: sql

我遇到了与多个不同表对应的SQL查询。我写了以下代码,但它似乎将每个预订与每张发票结合起来,而不是找到与特定预订相匹配的特定发票。任何帮助将不胜感激。

$sql = "SELECT INVOICE.invoice_id, 
           g.guest_first_name,
           g.guest_last_name, 
           g.booking_num_guests,
           g.booking_num_nights,
           CURRENCY.currency_name,
           INVOICE.invoice_nightly_rate,     
           INVOICE.invoice_deposit_amount,
           INVOICE.invoice_paid,
           ACCOUNT.account_name 
        FROM INVOICE    
        INNER JOIN BOOKING
             ON INVOICE.invoice_booking_id = BOOKING.booking_id
        INNER JOIN CURRENCY
             ON INVOICE.invoice_currency_id = CURRENCY.currency_id
        INNER JOIN ACCOUNT
             ON INVOICE.invoice_account_id = ACCOUNT.account_id
        INNER JOIN (
           SELECT GUEST.guest_first_name, 
                  GUEST.guest_last_name,
                  BOOKING.booking_num_guests,
                  BOOKING.booking_num_nights
           FROM BOOKING
           INNER JOIN GUEST
               ON BOOKING.booking_guest_id = GUEST.guest_id) g
               ON INVOICE.invoice_booking_id = BOOKING.booking_id";

1 个答案:

答案 0 :(得分:1)

由于您已在第一个内部联接中加入INVOICEBOOKING表,因此最后一个内部联接应位于BOOKINGGUEST表之间。将您的查询更改为以下

$sql = "SELECT 
            INVOICE.invoice_id, 
            GUEST.guest_first_name, 
            GUEST.guest_last_name, 
            BOOKING.booking_num_guests, 
            BOOKING.booking_num_nights, 
            CURRENCY.currency_name, 
            INVOICE.invoice_nightly_rate, 
            INVOICE.invoice_deposit_amount, 
            INVOICE.invoice_paid, 
            ACCOUNT.account_name 
        FROM INVOICE    
        INNER JOIN BOOKING 
            ON INVOICE.invoice_booking_id = BOOKING.booking_id
        INNER JOIN CURRENCY 
            ON INVOICE.invoice_currency_id = CURRENCY.currency_id
        INNER JOIN ACCOUNT 
            ON INVOICE.invoice_account_id = ACCOUNT.account_id
        INNER JOIN GUEST 
            ON BOOKING.booking_guest_id = GUEST.guest_id";