2012-09-13 212 views
1

我有簡單的查詢:選擇IF查詢

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`; 

所以我需要返回第一個查詢的值只有當第二個返回YES代表當前的ID。

+0

你會使用'JOIN'? –

回答

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

嘗試,

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` 
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' 
    ) 
+0

如果可以將'name_id'從查詢傳遞給子查詢? –

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`;