mysql - 在两个表上使用 where 子句使用 mysql left join 获取数据

标签 mysql sql

我有 2 个表,custom_leads_fieldscustom_leads_fields_optioncustom_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);

sqlfiddle

关于mysql - 在两个表上使用 where 子句使用 mysql left join 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52360517/

相关文章:

java - 使用 java 连接数据库 - 驱动程序错误

java.sql.SQLException : Access denied for user 'wineship' @'localhost' (using password: YES) 异常

mysql - 连接三个表,不显示所有记录

SQL 获取日期中 15 日第一次出现的情况

mysql - 复杂的sql语句,里面有4个条件

java - 与hibernate分组的其他字段一起计数

mysql - 如何将 MySQL 列从 VARCHAR 更改为日期时间并同时转换数据?

java - 如何让spring使用mysql而不是hsql

php - MySQL 事务时序

php - 将日期时间输出更改为今天并中断时间