我有 2 个表,custom_leads_fields
和 custom_leads_fields_option
。 custom_leads_fields
的主键
保存在custom_leads_fields_option
表中作为c_id
。
我需要从 custom_leads_fields
表中获取所有记录,其中 status = 1
然后我还需要从 custom_leads_fields_option
中匹配记录,其中 状态 = 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
即使 第二个表中没有记录
,它也应该从 第一个表中
,但是如果 返回记录
,然后第二个表
中的记录可用仅应获取那些
。status = 1
的记录
我写了一个查询,但它没有返回标签“A”,因为匹配的记录在其他表中不可用。
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
WHERE
(`custom_leads_fields`.`user_id`=591)
AND (`custom_leads_fields`.`status`=1)
AND (`custom_leads_fields_option`.`status`= 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);
关于mysql - 在两个表上使用 where 子句使用 mysql left join 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52360517/