如何在MySQL中获得“仅在存在时获取”?

时间:2011-03-20 23:48:25

标签: mysql

我的查询......

   SELECT MIN(p.`land_price`) AS `min_price`,
          MAX(p.`land_price`) AS `max_price`,
          p.`estate`,
          m.`file`

     FROM `properties` AS `p`
LEFT JOIN `estates` AS `e`
       ON p.`estate` = e.`title`

LEFT JOIN `media` AS `m`
       ON  m.`category` = e.`id` 

    WHERE p.`estate` IN ("EstateA", "EstateB")
      AND p.`land_price` != 0
 GROUP BY p.`estate

我想要做的是从media表中获取一个项目(别名为mname = "Profile",除了只选择是否存在,否则只有空白列结果集中的其他人。目前,如果我添加该约束,它只会给出name存在的匹配项。

目前,它只是选择media中与约束匹配的第一项。

1 个答案:

答案 0 :(得分:6)

“WHERE”部分限制主表properties的结果。在这种情况下,您应该为第二个LEFT JOIN的“ON”部分添加另一个约束。

示例:

SELECT MIN(p.`land_price`) AS `min_price`,
          MAX(p.`land_price`) AS `max_price`,
          p.`estate`,
          m.`file`

     FROM `properties` AS `p`
LEFT JOIN `estates` AS `e`
       ON p.`estate` = e.`title`

LEFT JOIN `media` AS `m`
       ON  m.`category` = e.`id` 
       AND m.`name` = 'Profile'

    WHERE p.`estate` IN ("EstateA", "EstateB")
      AND p.`land_price` != 0
 GROUP BY p.`estate