假設我有一個餐桌動物和一個1:n 關系的餐桌比賽。
餐桌動物看起來像:
| id_animal | 型別 |
|---|---|
| 1 | 貓 |
| 2 | 狗 |
表比賽看起來像:
| id_competition | fid_animal | 名稱 |
|---|---|---|
| 1 | 1 | 一個 |
| 2 | 2 | 一個 |
| 3 | 2 | 乙 |
這意味著貓參加比賽 A,狗參加比賽 A 和 B。
我現在想根據桌競賽中的條目過濾桌動物。
查詢聽起來像:
向我展示所有參加比賽(名稱)A 但不參加比賽的動物(型別)。結果應該只給我貓,而不是狗。
我用以下 sql(簡化)試試運氣:
Select DISTINCT * FROM animal
LEFT JOIN competition ON id_animal = fid_animal
WHERE competition.name IN ("A") AND NOT competition.name IN ("B");
結果我得到了貓和狗。只AND NOT把狗還給我,這很好,但兩者都沒有給我想要的結果。
我究竟做錯了什么?我怎樣才能實作輸出?
先感謝您!
Background: I have a bound form (datatable) with lot of entries and a table as data source. The user should be able to filter the form based on parameters in a related (1:n) table. So I made an unbound form with listboxes (populated with possible entries of the related table), where the user can choose multiple criteria. The result is a sql statement like above which is used as new data source for the bound form. This logic is working fine. Problem is that sometimes an entry in the form can have multiple parameters and for the user it is important to filter by chosen parameters but exclude the result if it contains specific other parameters. There are a few related tables, many listboxes are part of the filter and the sql string is generated dynamically, based on if and what the user selects.
uj5u.com熱心網友回復:
MS Access 通常遠不符合標準。以下是標準 SQL 中的簡單查詢,幾乎在每個 RDBMS 中運行:
SELECT *
FROM animal
WHERE id_animal IN (SELECT id_animal FROM competition WHERE name = 'A')
AND id_animal NOT IN (SELECT id_animal FROM competition WHERE name = 'B');
[NOT] IN適用于串列。在單項串列上使用它沒有什么意義。name IN ("A")是一樣的name = "A"。當您想在比賽表中查找動物串列時,您需要一個如上所示的子查詢。
如你所見,我不加入。我為什么要?我想選擇動物,所以我從動物表中選擇。我想將結果限制為某些動物,所以我使用了一個WHERE子句。
我注意到您對字串文字使用雙引號。如果這在 MS Access 中是必需的,則將上面的單引號替換為雙引號。(在標準 SQL 雙引號中分隔名稱,而不是字串文字,但這在 MS Access 中可能不同。)
uj5u.com熱心網友回復:
考慮:
SELECT animal.* FROM animal LEFT JOIN competition ON id_animal = fid_animal
WHERE [name]="A" AND NOT id_animal IN (SELECT fid_animal FROM competition WHERE [name]="B")
可能會發現這個相關的相關問題Microsoft Access - Filtering a form based on checkboxes for one field
uj5u.com熱心網友回復:
您需要查看幾行。你的謂詞:
WHERE competition.name IN ("A") AND NOT competition.name IN ("B");
針對同一行進行評估。它將查找名稱為“A”而不是“B”的所有行,即比賽 1 和 2。如果您查看名稱為“A”的行,其中不存在名稱為“B”的同一動物的行' 你會找到你要找的東西:
SELECT c1.fid_animal
FROM competition c1
WHERE c1.name = 'A'
AND NOT EXISTS (
SELECT *
FROM competition c2
WHERE c1.fid_animal = c2.fid_animal
AND c2.name = 'B'
)
現在您可以將此結果與動物連接起來以查找型別:
SELECT a.type
FROM competition c1
JOIN animal a
ON a.id_animal = c1.fid_animal
WHERE c1.name = 'A'
AND NOT EXISTS (
SELECT *
FROM competition c2
WHERE c1.fid_animal = c2.fid_animal
AND c2.name = 'B'
);
FWIW,type 是 SQL 中的保留字,因此您應避免將其用作識別符號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/423089.html
標籤:
上一篇:嘗試使用ShellExecute從Access中打開帶有按鈕的檔案
下一篇:HTTP狀態碼1XX深入理解
