我有一个像这样的SQL表:
------------------------------------------
ID | SKU | Name | Type
-------------------------------------------
2 | ABC | Pasta | 2
3 | XYZ | Maggi | 5
2 | ABC | Pasta | 5
6 | MNO | Macroni | 2
3 | XYZ | Maggi | 0
3 | XYZ | Maggi | 2
我需要找到类型为2但没有类型5或0的条目
的行例如: 它应该导致
------------------------------------------
ID | SKU | Name | Type
-------------------------------------------
6 | MNO | Macroni | 2
是否有可能仅使用这一张表?当然如此。 此表有1.4M行,我使用此查询(不确定它是否正确)
SELECT e1.* FROM reportmal e1, reportmal e2
WHERE e1.id= e2.id
AND e1.type=2 AND e2.type=5
查询从未返回任何内容,因为它仍在运行。 你能帮忙吗?
答案 0 :(得分:1)
我喜欢使用having
和group by
:
select e.id
from reportmal e
group by e.id
having sum(e.type = 2) > 0 and
sum(e.type in (0, 5)) = 0;
MySQL将布尔表达式视为数字上下文中的整数,其中“1”表示true,“0”表示false。因此sum(e.type = 2)
计算type = 2
中每个组中的记录数。 > 0
表示至少存在一个这样的行。 = 0
表示不存在此类行。
如果您想要原始行,可以join
将此结果返回到表格中。
答案 1 :(得分:1)
听起来像典型的“不存在”-query:
select * from atable result
where result.type = 2 and not exists
(select 1 from atable no50
where no50.type in (5,0)
and no50.sku = result.sku
)
或:
select * from atable result
where result.type = 2 and result.sku not in
(select sku from atable no50
where no50.type in (5,0)
)
答案 2 :(得分:0)
使用group by
尝试使用条件计数找到包含2而不是0或5的ID,然后使用IN
获取相关行。
select *
from your_table
where id in (
select
id
from your_table t
group by id
having count(case when type = 2 then 1 end) > 0
and count(case when type in (0,5) then 1 end) = 0
);
答案 3 :(得分:0)
select *
from reportmal e
where e.type = 2
and not exists
(
select null
from reportmal e2
where e2.id = e.id
and e2.type in (0,5)
)
至于表现问题 -
您需要的最小值是reportmal(id)的索引
报告(id,类型)索引可能更好。
答案 4 :(得分:0)
我认为你应该使用它:
manager.CreateIdentityAsync
它是这样的: "所有行为TYPE 2,并且NOT EXISTS一行具有相同的NAME和TYPE 5或0"
我不知道您的参数是什么来定义"条目"。也许你应该在子查询上添加SKU(这完全取决于你的数据模型)。
答案 5 :(得分:0)
你的查询很接近,但你加入了Id,它会给你一个笛卡尔积。
我就是这样做的。
<div class="row">
@foreach($photoGalleries as $photoGallery)
<div class="col-md-3">
<a href="{{ url('/photogalleries/' . $photoGallery->id) }}">
<img class="img-fluid" style="height: 200px; width: 200px;" src="/images/{{ $photoGallery->cover_image }}">
</a>
<h3>{{ $photoGallery->name }}</h3>
</div>
@endforeach
</div>
希望能帮到你。