![](/img/trans.png)
[英]How do I select rows from one table as CSV and insert into another table based on a key?
[英]How can I select all rows from one table, calculating a field value based on another table
我有一張桌子上的merchandises
和merchandise_groups_merchandise
。 后一個表是中間表,用於存儲在多個商品組中選擇的商品(多對多)。 從merchandises.id
到merchandise_groups_merchandise.merchandise_id
有一個關系。
我正在嘗試匯總一個查詢,以產生以下結果,列出merchandises
表中的所有商品,並且is_selected
是布爾值的布爾值,該布爾值由merchandise_id是否在特定merchandise_group的merchandise_groups_merchandise
表中確定。 並且, merchandise_groups_merchandise.group_id
由用戶指定。
我已經嘗試在兩個表之間進行LEFT聯接,但是,當然,它只返回組中間表中的實際商品。
我怎樣才能做到這一點?
-------------------------------
|id |title |is_selected
---------------------------
|1 |Tree |1
|2 |Log |0
|3 |Toy |1
這是我嘗試過的查詢的SQL:
PARAMETERS group_id Short;
SELECT IIf(IsNull([merchandise_groups_merchandise].[merchandise_id]),False,True) AS selected, merchandises.id, merchandises.title
FROM merchandises LEFT JOIN merchandise_groups_merchandise ON merchandises.id = merchandise_groups_merchandise.merchandise_id
WHERE (((merchandise_groups_merchandise.merchandise_group_id)=[group_id]));
一種方法是使用iif()
並exists
一個子查詢:
select m.*,
iif(exists (select 1
from merchandise_groups_merchandise as mgm
where m.id = mgm.merchandise_id and
mgm.merchandise_group_id = [group_id]
)), 1, 0) as IsInGroupFlag
from merchandizes as m
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.