多个连接与on和case返回错误的结果

时间:2017-07-14 12:21:05

标签: mysql sql mysqli

SELECT `apt`.`id` as `aprtid`,
    `apt`.`apt_no` as `aptno`,
    `apt`.`core` as `aptcore`,
    `apt`.`floor` as `aptfloor`,
    `apt`.`bd_code` as `aptbuld`,
    `bd`.`building_name` as `buldname`,
    `rs`.`resident_name` as `rsdntname`,
    `rs`.`resident_email` as `rsdntemail`,
    `rs`.`resident_phone` as `rsdntphone`,
    `rs`.`resident_pic` as `rsdntpic`
FROM `apartments` as `apt` 
INNER JOIN `buildings` as `bd`
    ON `bd`.`bd_code` = `apt`.`bd_code` 
INNER JOIN `residents` as `rs`
    ON `rs`.`apartment_no` = `apt`.`apt_no`
WHERE `apt`.`id` = '8'
ORDER BY `apt`.`id` DESC

当我使用此查询时,它以某种方式返回确认但是在与居民和公寓案件的连接中它不匹配和。 因为我在居民和公寓上匹配我有相同的公寓没有,但两个都有不同的建筑但作为输出它返回我的结果如何可能我在这个查询中做错了。为什么我得到的结果我认为和条件不起作用,但是。

1 个答案:

答案 0 :(得分:0)

据推测,您的join条件尚未完成。我猜:

FROM `apartments` as `apt` INNER JOIN
     `buildings` as `bd`
     ON `bd`.`bd_code` = `apt`.`bd_code` INNER JOIN
     `residents` as `rs`
     ON `rs`.`apartment_no` = `apt`.`apt_no` AND
         rs.bd_code = apt.bd_code

或者:

FROM `apartments` as `apt` INNER JOIN
     `buildings` as `bd`
     ON `bd`.`bd_code` = `apt`.`bd_code` INNER JOIN
     `residents` as `rs`
     ON `rs`.`apt_id` = `apt`.`apt_id`