mysql order by field row 即使为空也显示

mysql order by field row display even if empty

我有两个 table(bom 和 bom_parts)。需要内部连接并显示 stock_deduct,GRN_id,part_id 个字段。

Table 1(出生地):

Table 2 (bom_parts):

MySql查询:

SELECT 
    bom_part.stock_deduct,
    bom_part.GRN_id,
    bom.part_id 
FROM 
    bom 
    INNER JOIN 
    bom_part 
        ON bom_part.BOM_id=bom.id  
WHERE 
    batch_id='0' AND
    `sr_no`=23 
ORDER BY 
    FIELD(part_id, 34,8,36,6)

查询结果:

预期结果:

即使 part_id 字段在这种情况下为空 8, 6,我只想将 part_id 与 stock_deduct 字段显示为结果中有 1,如下所述。

Stock_deduct GRN_id part_id
1 6 34
2 9 34
3 GRN1 34
1 8
1 GRN3 36
2 GRN2 36
1 6

如您所见,预期结果中的第 4 行和第 7 行 table 为指定的 ORDER BY FIELD(part_id, 34,8,36,6) 顺序。

提前致谢。

我想你想要 left join 和过滤:

select coalesce(bp.stock_deduct, 1) as stock_deduct, bp.grn_id, b.part_id 
from bom b
left join bom_part bp on bp.bom_id = b.id  
where b.batch_id = 0 and b.sr_no = 23 and b.part_id in (34, 8, 36, 6)
order by field(part_id, 34, 8, 36, 6)

where 子句中 bom.part_id 的过滤器带来 bom 的相关行。我们将 table 部分带 left join,因此不匹配的 boms 不会被过滤掉。最后,coalesce()把缺失的stock_deduct变成了1