SELECT IF查询

时间:2012-09-13 06:17:50

标签: mysql sql

我有简单的查询:

SELECT max(`id`) as `name_id` , LEFT(`name`,LENGTH(`name`)-2) AS `name`, `status` 
 FROM `users`
WHERE `site` = 1
  AND `category` = 'some'

我只需要选择那些supp == YES

SELECT `model`.`supp`
  FROM `model`, `users`
 WHERE `users`.`name_id` = `name_id_from_the_first_query`
   AND `model`.`model_id` = `users`.`model_id`;

因此,只有当第二个为当前id返回YES时,我才需要返回第一个查询的值。

4 个答案:

答案 0 :(得分:1)

尝试此查询:

SELECT max(`id`) as `name_id` , LEFT(`name`, LENGTH(`name`)-2) AS `name`
       , `status` 
 FROM `users` 
     JOIN `model` 
       ON `model`.`model_id` = `users`.`model_id`
    WHERE `site` = 1 AND `category` = 'some'
      AND `model`.`supp` = 'YES';

答案 1 :(得分:1)

尝试,

SELECT  max(a.`id`) as `name_id` , 
        LEFT(`name`,LENGTH(a.`name`)-2) AS `name`, 
        a.`status`
FROM    `model` a 
        INNER JOIN `users` b
            ON a.`model_id` = b.`model_id`
WHERE    a.`site` = 1 AND
         a.`category` = 'some' AND
         b.`supp` = 'YES'
GROUP BY a.`name`, a.`status`

答案 2 :(得分:1)

这里有另一种选择:

SELECT max(`id`) as `name_id` , LEFT(`name`,LENGTH(`name`)-2) AS `name`, `status` 
 FROM `users`
WHERE `site` = 1
  AND `category` = 'some'
  AND id IN (SELECT `model_id`
               FROM `model`
              WHERE `supp` = 'YES'
             )
GROUP BY `name`, `status`;

答案 3 :(得分:0)

SELECT max(`id`) as `name_id` , LEFT(`name`, 
LENGTH(`name`)-2) AS `name`, `status` 
FROM `users` WHERE `site` = 1 AND `category` = 'some'
     and EXISTS
     ( 
       SELECT `model`.`supp` FROM `model` 
          WHERE `model`.`model_id` = `users`.`model_id`
                 and `model`.`supp`='Yes'
      )