PHP/MySQL : CAST/CASE if row + '_remove' exists then don't select

标签 php mysql sql casting case

我想在我的查询中包含一个非常具体的 CAST/CASE,但我不太确定该怎么做。这是我的 SQL 行:

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

我要执行的是:

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

最佳答案

我建议使用一个名为 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' 而不是列出您想要的所有类型。

关于PHP/MySQL : CAST/CASE if row + '_remove' exists then don't select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15269816/

相关文章:

sql - .MDF 数据库的 UnixODBC 驱动程序问题。或 : is there a way to easily extract a bunch of tables without an sql server?

php - mysqli - 如何在 0 个受影响的行上返回 false

javascript - 如何在<pre>标签的每一行末尾添加<br/>?

MySQL 查询 WHERE 包括 CASE 还是 IF?

mysql - 从一行链接到多个外部行

php - 使用ajax动态显示html表行中的sql数据

php - 如何使用 RedBeanPHP 显示表中的所有记录?

php - 在没有 pcntl_fork() 的情况下守护 PHP 脚本

sql - 在 SQL Server 中选择最后一个零右边的数字

sql - ORDER BY 列 = 值 desc|asc