2016-11-18 79 views
-3

之間,我有4個表:SQL加入不同的表

  • 客戶
  • 賬戶
  • 付款
  • 轉會

我想這使得無論是傳輸或客戶付款。付款表與客戶表相關聯,轉賬表與客戶表相關聯,而客戶表與客戶表相關聯。

我怎麼能寫一個返回做出任何支付或轉移客戶查詢?

SELECT customer.registration_os, Count(DISTINCT customer.customer_id) AS registrations 
FROM customer 
Inner Join account On customer.customer_id = account.customer_id 
INNER JOIN payment ON customer.customer_id = payment.customer_id 
LEFT JOIN transfer ON customer.customer_id= transfer.from_account 
WHERE customer.ts_created BETWEEN ? AND ? 
    AND customer.registration_source = ? 
GROUP BY customer.registration_os 

謝謝

+0

添加一些示例表數據和預期結果(以及格式化文本)。同時向我們展示您當前的查詢嘗試! – jarlh

+0

你應該直接詢問之前嘗試一些東西。 – Rupsingh

+0

請看看[如何提問](http://stackoverflow.com/help/how-to-ask) – Viki888

回答

0
SELECT * FROM Customers as t1 
LEFT JOIN Accounts as t2 ON t2.customer_id = t1.id // (Account table is linked to Customers) 
LEFT JOIN Payments as t3 ON t3.customer_id = t3.id // (Payments table is linked to Customers) 
LEFT JOIN Transfers as t4 ON t4.account_id = t2.id // (Transfers table is linked to Accounts) 
WHERE (condition) 

對於病症使用的參數基礎上表名在這裏,我給T1,T2,T3,T4你可以使用任何表中的條件。

0

我想這使得無論是轉賬或付款的客戶

在SQL中,UNION類似於邏輯OR

SELECT customer_id 
    FROM customer NATURAL JOIN account 
    UNION 
    SELECT customer_id 
    FROM customer NATURAL JOIN (SELECT from_account AS customer_id 
            FROM transfer) t