我有这个巨大的查询,可以从一系列关键字中过滤结果。
select distinct textures.id from textures
WHERE ((textures.id in (
select tt.texture_id
from tag_texture tt join tags t
on t.id = tt.tag_id
where t.name in ('tag1', 'tag2')
group by tt.texture_id
HAVING COUNT(DISTINCT t.id) = 2
)
) OR (textures.id in (
select ct.texture_id
from category_texture ct join categories c
on c.id = ct.category_id
where c.name in ('category1', 'category2')
group by ct.texture_id
HAVING COUNT(DISTINCT c.id) = 2
)
) OR (textures.id in (
select tex.id
from textures tex
where tex.name LIKE 'texturename'
group by tex.id
HAVING COUNT(DISTINCT tex.id) = 1
)
) ) AND textures.is_published = 1
问题在于,如果我搜索 texturename tag1 ,即使它们与标签无关,也会找到所有的texturename结果。但是,如果我搜索“tag1 tag2”,结果列表将被过滤掉(结果不仅仅是搜索tag1)。将这些OR更改为AND会更加明显地扩大结果。
合并这些结果的最佳方法是什么,这样每次过滤一个单词时,结果集都会缩小?
答案 0 :(得分:1)
将所有scope: {
callback: '='
}
更改为class HasOutput
{
public string Date;
public string Time;
public string Output()
{
return Date + " " + Time;
}
}
class Hour : HasOutput, IMoment
{
public Hour (string s)
{
string[] parts = s.Split(';');
this.Date = parts[0];
this.Time = parts[1];
}
}
class Day : HasOutput
{
public Day(Hour hour)
{
this.Date = hour.Date;
this.Time = hour.Time;
}
}
可以解决问题:
OR
此查询中无需使用AND
。您没有加入任何其他表,因此不会导致结果成倍增加。
如果您想在所有字段中搜索相同的关键字,并要求其中至少有一个与每个字段匹配,请删除SELECT id, name
FROM textures
WHERE ((textures.id in (
select tt.texture_id
from tag_texture tt join tags t
on t.id = tt.tag_id
where t.name in ('1k', 'test')
group by tt.texture_id
HAVING COUNT(DISTINCT t.id) = 2
)
) AND (textures.id in (
select ct.texture_id
from category_texture ct join categories c
on c.id = ct.category_id
where c.name in ('mine')
group by ct.texture_id
HAVING COUNT(DISTINCT c.id) = 1
)
) AND (textures.id in (
select tex.id
from textures tex
where tex.name LIKE '%apple%'
group by tex.id
HAVING COUNT(DISTINCT tex.id) = 1
)
) ) AND textures.is_published = 1
和DISTINCT
条款。
GROUP BY
我将HAVING
添加到关键字列表中,因为否则select textures.id, textures.name from textures
WHERE ((textures.id in (
select tt.texture_id
from tag_texture tt join tags t
on t.id = tt.tag_id
where t.name in ('1k', 'test', 'apple', 'mine')
)
) AND (textures.id in (
select ct.texture_id
from category_texture ct join categories c
on c.id = ct.category_id
where c.name in ('1k' 'test', 'apple', 'mine')
)
) AND (textures.id in (
select tex.id
from textures tex
where tex.name LIKE '%1k%' OR tex.name LIKE '%test%' OR tex.name LIKE '%apple%'
OR tex.name LIKE '%mine%'
)
) ) AND textures.is_published = 1
表中没有匹配。