【发布时间】:2013-12-24 08:28:48
【问题描述】:
我创建了以下查询以在视图中使用
SELECT
*
FROM
customers c
JOIN
customer_business cb
ON
c.customer_id = cb.customer_id
union
SELECT
*
FROM
customers c
LEFT JOIN
customer_business
ON
business_id=NULL;
这使他的工作完美无缺。它显示所有与该业务相关的客户,并在最后显示所有客户与该业务的信息为空。
customer_id | business_id
--------------------------------
1 | 1
2 | 1
2 | 2
1 | NULL
2 | NULL
3 | NULL
但是UNION使视图的性能很差的问题。
我尝试使用 LEFT JOIN 来实现,但没有显示所有业务为 null 的客户,只显示没有任何关联业务的客户
我知道加快查看速度的解决方案是删除那个 UNION,但我不知道怎么做。
谁能帮帮我?
谢谢
编辑
这是一个例子
Customer Table
customer_id | name
--------------------------------
1 | test1
2 | test2
3 | test3
Customer_business Table
customer_business_id | customer_id | business_id
----------------------------------------------------------
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 2 | 1
5 | 2 | 2
Expected query result:
name | customer_id | business_id
----------------------------------------------------------
test1 | 1 | 1
test1 | 1 | 2
test1 | 1 | 3
test2 | 2 | 1
test2 | 2 | 2
test1 | 1 | NULL
test2 | 2 | NULL
test3 | 3 | NULL
【问题讨论】:
-
我不明白查询的第二部分,idbusiness=NULL 条件是什么?它似乎加入了比你想要的更多的行。您是否试图让所有客户都没有对应的 customer_business 行?
-
提高性能的第 1 步是将 select * 替换为仅选择您需要的字段。
-
第 2 步是了解您自己的查询以及 null 和左连接的工作原理。
-
SQL 中的 UNION 运算符消除了结果中的重复项;为此,它必须对中间结果集进行排序。如果您希望保留重复项并避免排序,请改用 UNION ALL 运算符。
-
谢谢,我现在明白了我所做的大部分错误。
标签: mysql sql database optimization union