我知道类似的问题已经呈现过几次,但似乎这些都与基于特定字段值的字段值变化有关。我实际上想根据每条记录的字段值加入一个完全不同的表。
我认为这可以通过单个查询实现,但由于连接表可以更改每个记录,我不确定。
澄清我有四张桌子;我试图在一个查询中加入其中三个。但是,第三个表可以是两个表中的一个,具体取决于每个记录字段中的值。
我认为它会看起来像这样,但它不起作用。
SELECT crm_deal . * , crm_deal_step.sort_order, COALESCE( CONCAT_WS(' ',crm_lead.first_name, crm_lead.last_name),CONCAT_WS(' ',customer.firstname, customer.lastname) ) AS contact_full_name
FROM `crm_deal`
IF( crm_deal.deal_for = 'lead', LEFT JOIN crm_lead ON crm_deal.deal_for_id = crm_lead.lead_id, LEFT JOIN customer ON crm_deal.deal_for_id = customer.customer_id)
LEFT JOIN crm_deal_step ON crm_deal.deal_step_id = crm_deal_step.deal_step_id
我关门了吗?是否可能或者我是否需要执行php循环并为每条记录运行第二个查询?
答案 0 :(得分:0)
如果选择参数中的统计信息,则无法使用。 但你可以试试这个:
SELECT crm_deal . * , crm_deal_step.sort_order,
CASE WHEN crm_lead.first_name is not null AND
crm_lead.last_name is not null
THEN crm_lead.first_name+ ' '+crm_lead.last_name
ELSE customer.firstname +' '+ customer.lastname
END as contact_full_name
FROM `crm_deal`
LEFT JOIN crm_lead ON crm_deal.deal_for_id = crm_lead.lead_id AND crm_deal.deal_for = 'lead'
LEFT JOIN customer ON crm_deal.deal_for_id = customer.customer_id AND crm_deal.deal_for <> 'lead'
LEFT JOIN crm_deal_step ON crm_deal.deal_step_id = crm_deal_step.deal_step_id