使用mysql左连接在两个表上使用where子句获取数据

时间:2018-09-17 03:50:11

标签: mysql sql

我有2个表,custom_leads_fieldscustom_leads_fields_optionprimary key的{​​{1}}在custom_leads_fields表中另存为custom_leads_fields_option

我需要从c_id的{​​{1}}表中获取所有记录,然后我还需要从custom_leads_fields的{​​{1}}那里匹配记录

status = 1

需要的输出:

custom_leads_fields_option

即使status = 1,它也应从custom_leads_fields table c_id | user_id | label | status | 1 | 591 | A | 1 | 2 | 591 | B | 1 | 3 | 591 | C | 0 | custom_leads_fields_option table id | c_id | option | status 1 | 2 | yes | 1 2 | 2 | no | 1 3 | 2 | may | 0 4 | 3 | yy | 1 5 | 3 | zz | 1 c_id | label | option 1 | A | 2 | B | yes 2 | B | no ,但是如果return records中的first table if status = 1,则records are not available in second table的{​​{1}}。

我已经写了一个查询,但是它没有返回标签'A',因为其他表中没有匹配的记录。

records are available

2 个答案:

答案 0 :(得分:1)

您需要将状态条件移动到加入条件,这将提供您想要的输出。左表中的所有记录和右表中的匹配记录(状态为1的条件)

SELECT 
`custom_leads_fields`.`c_id` AS `field_id`, 
`custom_leads_fields_option`.`id` AS `option_id`, 
`custom_leads_fields`.`label`, 
`custom_leads_fields_option`.`option` 
FROM 
`custom_leads_fields` 
LEFT JOIN 
`custom_leads_fields_option` 
ON custom_leads_fields.id = custom_leads_fields_option.custom_leads_field_id 
AND (`custom_leads_fields_option`.`status`= 1) // changed line
// ^^^^^^^^^^^^^^^^^^
WHERE 
(`custom_leads_fields`.`user_id`=591) 
AND (`custom_leads_fields`.`status`=1) 

答案 1 :(得分:1)

我认为是左联接,标签A与custom_leads_fields_option表没有任何关系。因此,您不能使用custom_leads_fields_option.status = 1。你可以试试这个

select clf.*, clfo.*
from custom_leads_fields clf
left join custom_leads_fields_option clfo
on clf.id = clfo.c_id
where clf.status = 1
and (clfo.status = 1 or clfo.status is null);

sqlfiddle