我正在使用以下查询来检索所需的对象:
SELECT *
FROM tb_po_items
LEFT JOIN tb_materials ON tb_po_items.po_material = tb_materials.id_material
LEFT JOIN tb_services ON tb_po_items.po_service = tb_services.id_service
WHERE po_id =47
现在我需要添加以下内容:
条件1 - >如果tb_po_items.mos = 1则LEFT JOIN tb_units ON tb_materials.material_unit = tb_units.id_unit
其他
条件2 - >如果tb_po_items.mos = 2则LEFT JOIN tb_units ON tb_services.service_unit = tb_units.id_unit
如何在MySQL查询中实现这两个条件的使用?
提前致谢。
答案 0 :(得分:1)
这是实验性的,所以在你上线之前检查一下。
SELECT * FROM tb_po_items
IF(tb_po_items.mos = 1, LEFT JOIN tb_materials ON tb_po_items.po_material = tb_materials.id_material, LEFT JOIN tb_services ON tb_po_items.po_service = tb_services.id_service)
WHERE po_id =47
答案 1 :(得分:1)
试试这个:
SELECT *
FROM tb_po_items
LEFT JOIN tb_materials ON tb_po_items.po_material = tb_materials.id_material
LEFT JOIN tb_services ON tb_po_items.po_service = tb_services.id_service
LEFT JOIN tb_units ON (
(tb_materials.material_unit = tb_units.id_unit AND tb_po_items.mos = 1)
OR
(tb_services.service_unit = tb_units.id_unit AND tb_po_items.mos = 2) )
WHERE po_id =47;