[英]How to select all rows that don't have one-to-many entity with certain value using Doctrine
[英]SQL: Selecting IDs that don't have any rows with a certain value for a column
我想選擇不具有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
你可以使用
SELECT
id,
count(*) as Total
FROM table
WHERE val <> 'current'
HAVING Total > 0
產量
| ID | TOTAL |
|----|-------|
| 23 | 5 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.