小编典典

SQL:选择不包含任何具有特定值的行的ID的列

sql

我想选择不具有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语句。有没有更短的方法可以做到这一点?


阅读 379

收藏
2021-03-23

共1个答案

小编典典

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
2021-03-23