gpt4 book ai didi

php - SQL:选择没有任何行具有特定列值的 ID

转载 作者:可可西里 更新时间:2023-11-01 13:37:44 29 4
gpt4 key购买 nike

我想选择不包含 VAL = 'current' 的任何行的不同 ID(与多行关联)。

例如,在这样的表格中:

PK | ID | VAL 
-------------
1 | 23 | deleted
2 | 23 | deleted
3 | 23 | deleted
4 | 45 | current
5 | 45 | deleted
6 | 45 | deleted
...|................

我希望它返回 ID 23,因为它没有 VAL='current' 的行。请注意,在此表中,主键 (PK) 是唯一的,但 ID 不是(因此需要使用 DISTINCT 或 GROUP BY)。

这是我在 PHP 中的内容:

$conn = someConnect("");

// returns ids associated with the number of rows they have where VAL != 'current'
$sql = "SELECT id, count(*) FROM table WHERE val != 'current' GROUP BY id"

$stid = oci_parse($conn, $sql);
oci_execute($stid);

oci_fetch_all($stid, $arr, OCI_FETCHSTATEMENT_BY_ROW);

foreach ($arr as $elm) {
$id = key($elm);
$non_current_count = $elm[$id];

// counts the number of rows associated with the id, which includes VAL = 'current' rows
$sql2 = "SELECT count(*) FROM table WHERE id = $id";

$stid2 = oci_parse($conn, $sql2);
oci_execute($stid2);
$total_count = oci_fetch_array...
if ($total_count != $non_current_count) {
$output[] = $id;
}
...
}

oci_close($conn);

这就是它的一般要点。如您所见,需要两条 SQL 语句才能完成此任务。有更短的方法吗?

最佳答案

SELECT DISTINCT id
FROM table
WHERE id NOT IN (SELECT id
FROM table
WHERE val = 'current')

或:

SELECT a.id
FROM table a
LEFT JOIN table b ON a.id = b.id AND b.val = 'current'
WHERE b.id IS NULL

关于php - SQL:选择没有任何行具有特定列值的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20261960/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com