SQL条件下的IF语句

时间:2018-02-07 12:42:11

标签: mysql if-statement join

我尝试了通过此网站找到的许多解决方案,但仍无法找到解决问题的好方法。

我想列出warehouse_devices的所有记录,但是如果可能,我需要从devices获取其他数据(当它可以加入两个表时) 。我有一个特殊字段warehouse_devicesinstall = 1表示devices表中有相应的记录。

我尝试使用IF语句,CASE等,但我仍然没有成功。

这是我的陈述:

SELECT `wd`.`id` AS `wdId`,
       `wd`.`serial` AS `wdSerial`,
       `wd`.`serial_ap` AS `wdSerialAp`,
       `wd`.`status` AS `wdStatus`,
       `ex`.`name` AS `expertsName`,
       `ex`.`surname` AS `expertsSurname`,
       `t`.`name` AS `typesName`,
       `o`.`name` AS `ownersName`,
       `t`.`mark` AS `typesMark`,
       `d`.`next_visit` AS `devicesNextVisit`,
       `d`.`id_dev` AS `devicesIdDev`
FROM `warehouse_devices` `wd` LEFT JOIN `experts` `ex` ON `wd`.`expert`=`ex`.`id`
                              LEFT JOIN `types` `t` ON `wd`.`type`=`t`.`id`
                              LEFT JOIN `owners` `o` ON `o`.`id`=`wd`.`owner`
                              LEFT JOIN `devices` `d` ON `d`.`warehouse_devices`=`wd`.`id`

2 个答案:

答案 0 :(得分:1)

只需在on子句中包含条件:

FROM `warehouse_devices` `wd` LEFT JOIN
     `experts` `ex`
     ON `wd`.`expert`=`ex`.`id` LEFT JOIN
     `types` `t`
     ON `wd`.`type`=`t`.`id` LEFT JOIN
     `owners` `o`
     ON `o`.`id`=`wd`.`owner` LEFT JOIN
     `devices` `d`
     ON `d`.`warehouse_devices` = `wd`.`id` and wd.install = 1

答案 1 :(得分:0)

尝试使用set operation UNION

warehouse_devices.install=1

时,您可以在不加入设备表和加入设备表的情况下获取记录

查询应如下所示

SELECT `wd`.`id` AS `wdId`,
       `wd`.`serial` AS `wdSerial`,
       `wd`.`serial_ap` AS `wdSerialAp`,
       `wd`.`status` AS `wdStatus`,
       `ex`.`name` AS `expertsName`,
       `ex`.`surname` AS `expertsSurname`,
       `t`.`name` AS `typesName`,
       `o`.`name` AS `ownersName`,
       `t`.`mark` AS `typesMark`,
       ``,
       ``
FROM `warehouse_devices` `wd` LEFT JOIN `experts` `ex` ON `wd`.`expert`=`ex`.`id`
                              LEFT JOIN `types` `t` ON `wd`.`type`=`t`.`id`
                              LEFT JOIN `owners` `o` ON `o`.`id`=`wd`.`owner`

                              UNION

     SELECT `wd`.`id` AS `wdId`,
       `wd`.`serial` AS `wdSerial`,
       `wd`.`serial_ap` AS `wdSerialAp`,
       `wd`.`status` AS `wdStatus`,
       `ex`.`name` AS `expertsName`,
       `ex`.`surname` AS `expertsSurname`,
       `t`.`name` AS `typesName`,
       `o`.`name` AS `ownersName`,
       `t`.`mark` AS `typesMark`,
       `d`.`next_visit` AS `devicesNextVisit`,
       `d`.`id_dev` AS `devicesIdDev`
FROM `warehouse_devices` `wd` LEFT JOIN `experts` `ex` ON `wd`.`expert`=`ex`.`id`
                              LEFT JOIN `types` `t` ON `wd`.`type`=`t`.`id`
                              LEFT JOIN `owners` `o` ON `o`.`id`=`wd`.`owner`
                              LEFT JOIN `devices` `d` ON `d`.`warehouse_devices`=`wd`.`id`  AND wd.install=1