[英]How can I select all rows from one table, calculating a field value based on another table
I have a table merchandises
and merchandise_groups_merchandise
. 我有一张桌子上的merchandises
和merchandise_groups_merchandise
。 The latter table is the middle table for storing which merchandise is selected inside which merchandise groups - a many to many. 后一个表是中间表,用于存储在多个商品组中选择的商品(多对多)。 There's a relation from merchandises.id
to merchandise_groups_merchandise.merchandise_id
. 从merchandises.id
到merchandise_groups_merchandise.merchandise_id
有一个关系。
I'm trying to put together a query to produce the following results, listing all the merchandise from the merchandises
table and where is_selected
is a boolean decided by whether the merchandise_id is in the merchandise_groups_merchandise
table for a specific merchandise_group. 我正在尝试汇总一个查询,以产生以下结果,列出merchandises
表中的所有商品,并且is_selected
是布尔值的布尔值,该布尔值由merchandise_id是否在特定merchandise_group的merchandise_groups_merchandise
表中确定。 And, the merchandise_groups_merchandise.group_id
is specified by the user. 并且, merchandise_groups_merchandise.group_id
由用户指定。
I've tried a LEFT join, between the two tables, but of course, that only returns the actual merchandise that's in the group middle table. 我已经尝试在两个表之间进行LEFT联接,但是,当然,它只返回组中间表中的实际商品。
How can I do this? 我怎样才能做到这一点?
-------------------------------
|id |title |is_selected
---------------------------
|1 |Tree |1
|2 |Log |0
|3 |Toy |1
This is the SQL of the query that I've tried: 这是我尝试过的查询的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]));
One method is with iif()
and an exists
subquery: 一种方法是使用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.