1

I want a include a very specific CAST/CASE in my query, but I'm not really sure how to do this. Here is my SQL LINE :

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

What I'm trying to perfom is that :

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

Example, and what I want the query to select or not :

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
2
  • 1
    If points is a numeric datatype, surely you simply check for < 0; if it isn't numeric, why isn't it?
    – Mark Baker
    Mar 7, 2013 at 11:23
  • Cool! Yeah points is a BIGINT(20) So yeah I'm going to do that :) Thinx
    – hawkidoki
    Mar 7, 2013 at 11:26

1 Answer 1

2

I would suggest using a field called removed, which would make the whole thing much easier/cleaner, but if you have your reasons, you could try this:

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;

Also, if you're going to have the same basic setup for many types, you could just select type NOT LIKE '%_remove' instead of listing all the types you want.

1
  • Think you dude! I'm currently testing it
    – hawkidoki
    Mar 7, 2013 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.