我创建了以下表格:
客户表:
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
您可能想要将Customer.cust_id添加到两个查询列列表中.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。