[英]Adding null values for records not existing in joined table
我有一个名为top_trends
的表,它具有以下架构:
id int(11) AI PK
criteria_id int(11)
value varchar(255)
created_at timestamp
updated_at timestamp
然后我有另一个表,称为search_criterias
,它具有以下架构:
id int(11) AI PK
title varchar(255)
created_at timestamp
updated_at timestamp
这是一个查询,它根据一个值提供基于最大记录数的值。 因此,如果在top_trends
有 2 条记录, top_trends
criteria_id
为 1,并且在top_trends.value
列中的值都为 3,然后有一个单独的 SINGLE 记录,具有相同的criteria_id 1 但值为 2,则查询将产生一个结果所选条件(为 1)的值为 3,因为值 3 比任何其他具有criteria_id 1 的值行出现的次数更多。因此,简单来说,查询为条件 id 1 选择了值 3,因为这发生了基于具有criteria_id
1的top_trends中的记录的最多次数
select
x.value as `values`
, sc.id as id
, sc.title
, sc.created_at
, sc.updated_at
, x.criteria_id as search_category_id
from
(
select
criteria_id
, `value`
from
top_trends
group by
`criteria_id`
order by
`value`
) x
left join search_criterias sc
on sc.id = x.criteria_id
group by
criteria_id
我的问题是,不幸的是,现在我们没有所有可能的search_criterias
的数据,所以search_criteria
表中的一些记录没有在我的查询中聚合。
例如,我们有一个城市的 search_criteria 记录,id 为 5,但 top_trends 表中没有criteria_id 为 5 的记录......所以上面的查询不包括该 search_criteria。
我想做的是将那些不在top_trends
表中但values
属性为null
记录包含在search_criteria
表中
当左表中的行在右表中没有匹配项时,将使用LEFT JOIN
。 由于您的案例中缺少的行在top_trends
,因此应该是LEFT JOIN
的右表。 所以切换join的顺序。
select
x.value as `values`
, sc.id as id
, sc.title
, sc.created_at
, sc.updated_at
, x.criteria_id as search_category_id
from search_criterias sc
left join
(
select
criteria_id
, `value`
from
top_trends
group by
`criteria_id`
order by
`value`
) x
on sc.id = x.criteria_id
group bysc.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.