如果特定记录不存在,如何仅 SELECT 数据

How to only SELECT data if a specific record is not exist

我正在尝试显示多个具有条件的数据,如果特定记录存在于 MySQL 中的相同 table 中,则跳过行。

这是 table

的示例

table_a

|      id     |     bi_id    |     status     |
|-------------|--------------|----------------|
|          1  |         111  |process1        |
|          2  |         112  |process1        |
|          3  |         112  |process2        |
|          4  |         113  |process1        |
|          5  |         111  |process2        |
|          6  |         111  |done            |
|          7  |         112  |done            |

我正在使用下面的查询 select 状态为“完成”的最后一个 ID

SELECT MAX(id) FROM table_a WHERE status="done" GROUP BY bi_id

我想在状态不是“完成”的地方显示最后一个 ID,如果存在状态为“完成”的 bi_id,则不要 select 最大 ID,就像这样 table 下面。

预期结果:

------------------
|    max(id)     |
|----------------|
|       4        |

我最后一次尝试使用此查询,但如您所知,这是行不通的。我也尝试过使用 NOT EXIST 进行查询,但也没有用。

SELECT MAX(id)
FROM   table_a
WHERE status != "done" NOT IN
     (SELECT id
     FROM   table_a
     WHERE  status = "done" GROUP BY bi_id) GROUP BY by_id

是否有任何解决方法可以通过 MySQL 查询或 php/codeigniter 来实现? 谢谢,抱歉英语不好。

试试这个查询:

SELECT MAX(`id`)
FROM `table_a`
WHERE `status` != 'done'
AND `bi_id` NOT IN (
  SELECT `t2`.`bi_id`
  FROM `table_a` AS `t2`
  WHERE `t2`.`status` = 'done'
);

通过这种方式,您可以排除具有 bi_idstatus = 'done' 的行。 您可以在 DBFiddle.

中看到结果

您可以这样简单地进行查询:

SELECT MAX(id)
 FROM table_a
 GROUP BY bi_id
HAVING GROUP_CONCAT(status) NOT LIKE '%done%'

在上面的查询示例中,我使用了 GROUP BYGROUP_CONCAT() 函数。基本上,我对查询所做的是:

SELECT bi_id, GROUP_CONCAT(status), MAX(id) 
 FROM table_a
 GROUP BY bi_id;

哪个 return:

+-------+------------------------+---------+
| bi_id | GROUP_CONCAT(status)   | MAX(id) |
+-------+------------------------+---------+
| 111   | process1,process2,done |    6    |
| 112   | process1,process2,done |    7    |
| 113   | process1               |    4    |
| 114   | process2,process1      |   10    |
+--------------------------------+---------+

如您所见,111 & 112bi_id 具有 GROUP_CONCAT(status) 的结果,其中包含 done。所以在查询的时候过滤掉了这两个HAVING GROUP_CONCAT(status) LIKE '%done%'.

Demo fiddle

P/S:考虑到最后一条评论,我在示例中添加了另外两行 (8,114,'process2'), (10,114,'process1')