具有多个独立左联接的单个查询

时间:2019-08-06 11:00:00

标签: mysql join left-join

我有两个桌子。一种用于元素(线索),另一种用于元素属性(leads_properties)。

对解决此问题有用的铅表格列是:id,token。 属性表如下所示:

id      label      value
1       phone      555333666
3       phone      111222555
3       city       Milan

我正在尝试通过单个查询提取销售线索和所有请求的属性。如果我要求城市,我将只检索加入了城市财产的所有潜在客户信息,如果我要求城市和电话,我甚至将检索电话。

我正在尝试的查询是:

SELECT leads.* ,
p1.value as 'phone' ,
p2.value as 'city'
FROM leads
LEFT JOIN leads_properties as p1 ON leads.id = p1.lead_id 
LEFT JOIN leads_properties as p2 ON leads.id = p2.lead_id 
WHERE leads.id = 1 
AND p1.label = 'phone' 
AND p2.label = 'city' 
AND leads.token = 'xxxxx'
LIMIT 1

如果所有请求的属性都存在于数据库中(在此示例中,潜在客户id = 3)但是失败并为没有id“ city”属性的潜在客户id = 1返回0行,这将非常有用。

我理解为什么(WHERE语句中的AND子句可能是限制性的),但我不知道如何解决该问题。

我想这样检索一行(如果所有请求的属性都在数据库中)

id   token        city      phone
3    xxxxx        Milan     111222555

或者如果某些请求的属性不在数据库中,则这样(具有空值或NULL值):

id   token        city      phone
1    xxxxx                  111222555

非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用conditional aggregation来使用case when expression

SELECT leads.id,max(case when p1.label = 'city' then p1.value end) as city
max(case when p1.label = 'phone' then p1.value end) as phone
FROM leads
LEFT JOIN leads_properties as p1 ON leads.id = p1.lead_id
WHERE leads.id = 1 
group by leads.id

答案 1 :(得分:0)

这不是AND限制,而是询问p2.label = 'city'。如果您想要任何财产,您可能只是要求避免重复。例如:

    SELECT leads.* ,
    p1.value as 'phone' ,
    p2.value as 'city'
    FROM leads
    LEFT JOIN leads_properties as p1 ON leads.id = p1.lead_id 
    LEFT JOIN leads_properties as p2 ON leads.id = p2.lead_id 
    WHERE leads.id = 1 
    AND p1.label > p2.label
    AND leads.token = 'xxxxx'
    LIMIT 1