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

7

我希望选择那些具有多行关联的独特ID,且这些ID没有任何VAL = 'current'的行。

例如,在像这样的表中:

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语句。是否有更简单的方法呢?


你的期望输出是什么? - Muhammad Raheel
我想选择所有没有与之关联的行中VAL = 'current'的ID。 - George Newton
你使用的是哪个数据库管理系统? - user330315
3个回答

17
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

哇,我没想到这么简单。谢谢! - George Newton

1

你可以使用“having”

SELECT
    id,
    count(*) as Total
FROM table
WHERE val <> 'current'
HAVING Total > 0

输出

| ID | TOTAL |
|----|-------|
| 23 |     5 |  

小提琴


0

如果您想使用 Having 子句,则可以像这样使用

SELECT
    id,
    count(*) as Total
FROM Status S1
WHERE val <> 'current'
GROUP BY id
HAVING count(*) = (SELECT COUNT(*) FROM Status S2 WHERE S2.id = S1.id)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接