我想使用 mysql 来检查 MySQL 数据库中是否存在一个值。如果该值存在,我什么都不想做(我不想获取任何数据)。如果它不存在,那么我想设置一些where
条件。
所以这是我到目前为止所拥有的,但这是不对的。因为如果没有设置where
条件,我仍然会获取数据
SELECT *,
CASE
WHEN ( table_name.record = 'inputrecord')
THEN
//Do nothing because it is found already
ELSE
// since inputrecord does not exist, we will start looking for 'id'
( WHERE table_name.id = '123')
END
FROM table_name
注意:在上面的例子中,我写了WHEN ( table_name.record = 'inputrecord')
而不是 WHEN ( table_name.record != 'inputrecord')
. 这是因为我只想在数据不在表中时继续查询。
也许它能够更好地使用IF
功能与EXISTS
功能,但我不知道该怎么做。
任何帮助都会很棒。现在我收到错误
这不是 SQL 的工作方式。
SQL 总是返回行的集合。它可能是空的,有时行可能包含 NULL。您必须计算出过滤集合的条件。
一个通用示例:假设我们有一个带有列(型号、颜色、年份)的汽车表格,您想在表格中找到有关汽车的信息:
(* Find all red cars *)
select * from cars where color = 'red'
(* Find all red cars from 1985 *)
select * from cars where color = 'red' and year = 1985
(* Find all colors which exist both in 1990 and 2000 *)
select distinct color from cars A where year=1990 and exists (select 1 from cars B where year=2000 and B.color = A.color)
请准确说出您想要达到的目标
编辑:这应该这样做
(* select a record cars = 'Audi' only if cars = 'BMW' is not found in the whole table. otherwise. I do not want to select Audi even if it exists *)
select * from cars where model = 'Audi' and not exists (select 1 from cars where model = 'BMW')
在这里,如果你的表中有宝马,你会得到 0 行,否则是奥迪的列表
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句