在 MySQL select 查询中,检查字符串或在 where 子句中检查 true?
In MySQL select query, checking for a string or checking for true in a where clause?
考虑以下 table:
SELECT id, Bill_Freq, Paid_From, Paid_To, Paid_Dt, rev_code FROM psr_20160708091408;
要求是获取 rev_code
填充了字符串 **SUM
** 的行。
我还注意到,对于 rev_code
填充为 **SUM
** 的每一行,其 Bill_Freq
不会为空或零。
所以我写了两个查询来获取 id 最低的行
基于 where 子句中的字符串检查的查询:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**";
根据真实条件查询:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where bill_freq;
没见过有人用过第二种,想知道它的可靠性和故障情况。
实际上你可以使用第二种类型的查询,但是由于你的要求是基于rev_code,所以最好有条件rev_code,因为2个原因
- Bill_Freq 没有 NULls 或零可能是基于当前数据的假设
- 即使它是真的,将来您的应用程序逻辑可能会发生变化,并且它可能具有 NULL 或零的场景,这将在将来破坏您的逻辑。
所以我的建议是使用 Rev_code
的第一个查询
请尝试使用以下查询
select
id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**" ORDER BY ASC LIMIT 0,1;
谢谢。
如果 "second type" 是指没有明确条件的 where
子句,那么您有充分的理由看不到它。
SQL 标准——以及大多数数据库——需要在 where
中明确条件。 MySQL 允许您使用 shorthand 但它实际上意味着:
where not billing_freq <=> 0
或等同于:
where billing_freq <> 0 or billing_freq is null
(<=>
是 null 安全比较运算符。
您的查询中更重要的问题是 min()
。我猜你真的想要这个:
select p.*
from psr_20160708091408 p
where rev_code = '**SUM**'
order by id
limit 1;
此外,您应该使用单引号作为字符串分隔符。这是 ANSI 标准,几乎没有理由使用双引号。
需求说明了一切。
The requirement is to fetch the row which has rev_code populated with
the string '**SUM**'
在 bill_freq IS NOT NULL 和 rev_code
填充的情况下
字符串 '**SUM**'
那么你的逻辑显然会失败。
争取
where rev_code = "**SUM**";
考虑以下 table:
SELECT id, Bill_Freq, Paid_From, Paid_To, Paid_Dt, rev_code FROM psr_20160708091408;
要求是获取 rev_code
填充了字符串 **SUM
** 的行。
我还注意到,对于 rev_code
填充为 **SUM
** 的每一行,其 Bill_Freq
不会为空或零。
所以我写了两个查询来获取 id 最低的行
基于 where 子句中的字符串检查的查询:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**";
根据真实条件查询:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where bill_freq;
没见过有人用过第二种,想知道它的可靠性和故障情况。
实际上你可以使用第二种类型的查询,但是由于你的要求是基于rev_code,所以最好有条件rev_code,因为2个原因
- Bill_Freq 没有 NULls 或零可能是基于当前数据的假设
- 即使它是真的,将来您的应用程序逻辑可能会发生变化,并且它可能具有 NULL 或零的场景,这将在将来破坏您的逻辑。
所以我的建议是使用 Rev_code
的第一个查询请尝试使用以下查询
select
id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**" ORDER BY ASC LIMIT 0,1;
谢谢。
如果 "second type" 是指没有明确条件的 where
子句,那么您有充分的理由看不到它。
SQL 标准——以及大多数数据库——需要在 where
中明确条件。 MySQL 允许您使用 shorthand 但它实际上意味着:
where not billing_freq <=> 0
或等同于:
where billing_freq <> 0 or billing_freq is null
(<=>
是 null 安全比较运算符。
您的查询中更重要的问题是 min()
。我猜你真的想要这个:
select p.*
from psr_20160708091408 p
where rev_code = '**SUM**'
order by id
limit 1;
此外,您应该使用单引号作为字符串分隔符。这是 ANSI 标准,几乎没有理由使用双引号。
需求说明了一切。
The requirement is to fetch the row which has rev_code populated with the string '**SUM**'
在 bill_freq IS NOT NULL 和 rev_code
填充的情况下
字符串 '**SUM**'
那么你的逻辑显然会失败。
争取
where rev_code = "**SUM**";