【发布时间】:2014-08-08 23:15:15
【问题描述】:
我被困在 1 个查询中。我想在 1 个网格/行中显示客户的所有产品以及系统收到的所有短信。我可以做到这一点,但问题是只显示客户产品我需要 3 4 个其他表来加入并显示所有数据,如产品型号、客户名称等。其他的东西来自其他表。所以我需要 2 个表来做外连接,并显示来自 4 5 个表的数据。我试过了,但失败了。
Select tcp.*
, concat(tc.firstname,' ',tc.lastname) as cust_id
, tc.mobile
, tb.brand_name as brand
, tgt.gadget_type as gadget_type
, tm.model_name as model
, ttt.ticket_type as ticket_type
, trs.registration_source as registration_source
From tbl_cust_products tcp
Left Join `tbl_received_sms` trsm on tcp.id = trsm.cust_prod_id
Left Join tbl_customer tc on tcp.cust_id=tc.id
Left Join tbl_brand tb on tcp.brand = tb.id
Left Join tbl_gadget_type tgt on tcp.gadget_type=tgt.id
Left Join tbl_model tm on tcp.model = tm.id
Left Join tbl_ticket_type ttt on tcp.ticket_type=ttt.id
Left Join tbl_registration_source trs on trs.id=tcp.registration_source
Where tcp.del_date is NULL
Union
Select tcp.*
, concat(tc.firstname,' ',tc.lastname) as cust_id
, tc.mobile
, tb.brand_name as brand
, tgt.gadget_type as gadget_type
, tm.model_name as model
, ttt.ticket_type as ticket_type
, trs.registration_source as registration_source
From tbl_cust_products tcp
Right Join `tbl_received_sms` trsm on tcp.id=trsm.cust_prod_id
Left Join tbl_customer tc on tcp.cust_id=tc.id
Left Join tbl_brand tb on tcp.brand=tb.id
Left Join tbl_gadget_type tgt on tcp.gadget_type=tgt.id
Left Join tbl_model tm on tcp.model = tm.id
Left Join tbl_ticket_type ttt on tcp.ticket_type=ttt.id
Left Join tbl_registration_source trs on trs.id=tcp.registration_source
Where tcp.del_date is NULL
在上面我只想在tbl_cust_products 和tbl_received_sms 表上进行外连接。我在这里尝试了 outer join 的联合。当我搜索并发现 MySql do not support direct outer join 和其他大型数据库处理程序一样。
如果我在使用 union 或任何逻辑时犯了任何错误,请帮助我实现这一点..
已编辑
问题:
tbl_received_sms 有 7,734 条记录,tbl_cust_products 有 3 条记录。所以我需要总共 7737 条记录。如果我只使用UNION,我会得到3条记录,如果我使用UNION ALL,我会得到7737条记录,但所有记录的所有字段都是NULL。
【问题讨论】:
-
您只想要
tbl_cust_products和tbl_received_sms之间的外连接?每个查询有 7 个外部联接。Left Join、Right Join和Full Join都是outer joins的类型。outer关键字只是可选的。 -
您是否尝试过终止联合并将第一个联接更改为
Full Join? -
尝试使用
UNION ALL而不是UNION -
如果我使用 UNION ALL 所有数据都为 NULL
-
您的语法看起来不错。您遇到的实际问题是什么?查询是否失败,带回错误的数据或太慢。顺便说一句,查询的第二部分带回 tbl_received_sms 的记录,并将其与 tml_cust_products 匹配。如果没有匹配的记录,那么您在 SELECT 中返回的每个字段都将为 NULL。因此,UNION 将消除它们,除了一个(因为它们将被视为重复项)。任何在 tbl_cust_products 上匹配的内容都会被第一个选择带回来。 UNION ALL 只会带回大量 NULL 行
标签: php mysql sql join full-outer-join