2013-03-07 46 views
1

我想在我的查詢中包含一個非常具體的CAST/CASE,但我不確定如何執行此操作。這是我的SQL LINE:Php/Mysql:CAST/CASE如果row +'_remove'存在,那麼不要選擇

SELECT * FROM table WHERE (

     type = 'aaa' OR 
     type = 'bbb' OR 
     type = 'ccc' OR 
     type = 'ddd') 

     AND (points NOT LIKE '-%') 

     ORDER BY id DESC LIMIT 10 

什麼我試圖perfom是:

if : 'type'_remove EXISTS and 'type'->data == 'type'_remove->data 
then : Don't select the 'type' row. 

例子,我希望查詢選擇與否:

id type   data points 
---------------------------------- 
1  aaa   1  1  don't select : aaa_remove exists and data are the same 
2  bbb   1  3  select  : bbb_remove exists BUT data aren't the same 
3  ddd   1  -1  don't select : points IS LIKE '-%' 
4  aaa_remove  1  -1 
5  ddd   1  -3  don't select : points IS LIKE '-%' 
6  bbb_remove  2  -1 
7  ccc   1  1  select  : ccc_remove doesn't exists with the same data 
+1

如果points是一個數字數據類型,那麼你只需檢查'<0';如果它不是數字,爲什麼不是? – 2013-03-07 11:23:51

+0

酷!是的點是一個BIGINT(20)所以是的,我打算這麼做:) Thinx – hawkidoki 2013-03-07 11:26:13

回答

2

我建議使用名爲removed的字段,這可以使整個事情變得更容易/更清潔,但是如果你有自己的理由,你可以試試這個:

SELECT * 
FROM `table` AS `outer` 
WHERE 
    `outer`.`type` IN('aaa', 'bbb', 'ccc', 'ddd') AND 
    `outer`.`points` >= 0 AND 
    (
     SELECT `inner`.`id` 
     FROM `table` AS `inner` 
     WHERE 
      `inner`.`type` = CONCAT(`outer`.`type`, '_remove') AND 
      `inner`.`data` = `outer`.`data` 
     LIMIT 1 
    ) IS NULL 
ORDER BY `outer`.`id` DESC 
LIMIT 10; 

此外,如果您打算爲多種類型使用相同的基本設置,則可以選擇type NOT LIKE '%_remove'而不是列出所需的所有類型。

+0

認爲你哥們!我目前正在測試它 – hawkidoki 2013-03-07 12:17:37

+0

太棒了!它完美的工作!薄型:) – hawkidoki 2013-03-07 12:26:14

相關問題