我创建了以下表格:
客户表:
flag | cust_id | customer
--------------------------------
1 | 60 | customer1
0 | 61 | customer2
0 | 62 | customer3
帐户表:
acc_id | cust_id | account_name
------------------------------------
1 | 62 | account1
2 | 63 | account2
3 | 62 | account3
4 | 62 | account4
联系人表:
con_id | cust_id | contact_name
------------------------------------
1 | 60 | contact1
2 | 60 | contact2
3 | 61 | contact3
4 | 62 | contact4
如果客户表中的flag == 1,那么我需要使用以下条件来获取数据:我需要客户表中的所有行,否则标志== 0,那么我需要联系人表中的所有行.
如何一口气做到这一点?
有人可以帮我吗?
解决方法:
我猜您需要2个JOIN的UNION.
就像是:
-- SELECT the items from Customer and Accounts WHERE flag = 1
SELECT Customer.customer, Accounts.account_name AS Name FROM Customer
INNER JOIN Accounts ON Customer.cust_id = Accounts.cust_id
WHERE Customer.flag = 1
-- MERGE the 2 queries WITHOUT duplicates (use UNION ALL if you want the duplicates)
UNION
-- SELECT the items from Customer and Contacts WHERE flag = 0
SELECT Customer.customer, Contacts.contacts_name AS Name FROM Customer
INNER JOIN Contacts ON Customer.cust_id = Contacts.cust_id
WHERE Customer.flag = 0