我不知道它是否正确,但请查看以下架构:
实体可以是承运人或客户。每个客户都必须与承运人相关联,该承运人可以是自己的客户。
我遇到困难,尝试没有成功执行单个查询,该查询返回客户的 NAME 以及其运营商的 NAME 。有没有办法进行这样的操作?
由于
答案 0 :(得分:2)
我将id_carrier解释为运营商的实体ID:
select ec.name as CustomerName, eca.name as CarrierName
from customer c join
entity ec
on c.id_entity = e.id_entity join
entity eca
on c.id_carrier = eca.id_entity
这消除了加入运营商表的需要,除非您需要其他信息。
答案 1 :(得分:2)
您需要针对entity
表加入两次,每种类型一次。使用他们的别名(下面的ca, cu
)来引用SELECT
列表中的每个。
SELECT
/* Carrier info */
ca.id_entity AS carrier_id_entity,
ca.name AS carrier_name,
ca.date AS carrier_date,
carrier.carrier_stuff,
/* Customer info */
cu.id_entity_as AS customer_id_entity,
cu.name AS customer_name,
cu.date AS customer_date,
customer.discount,
customer.payment
FROM
carrier
JOIN customer ON customer.carrier_id = carrier.id_entity
/* JOIN first against entity for carrier */
JOIN entity ca ON carrier.id_entity = ca.id_entity
/* and again between customer and entity */
JOIN entity cu ON customer.id_entity = cu.id_entity
答案 2 :(得分:2)
加入entity
两次并提供name
列别名。如果不需要其他carrier
字段,请删除最后一个联接。
select customer_entity.name as customer_name, customer.credit, -- additional customer fields...
carrier_entity.name as carrier_name, carrier.carrier_stuff -- additional carrier fields...
from entity as customer_entity
inner join customer on (customer.id_entity = customer_entity.id_entity)
inner join entity as carrier_entity on (customer.id_carrier = carrier_entity.id_entity)
inner join carrier on (carrier.id_entity = carrier_entity.id_entity)