我想在SELECT Query中使用IF语句。这是样本。 我有3个表,可以保存客户信息,模型信息和库存。我想为每个客户提供最合适的型号。因此,在我的第一次尝试中,如果客户收入少于5000我想提供该商店中存在的廉价模型,否则该商店中的任何模型。 但我不能在SELECT WHERE部分使用IF clouse。
SELECT TOP 1 @vmodel = stocks.model , @vsloc = stocks.sloc , @vyear = models.year , @vcost = models.cost <br>FROM bistore.dbo.stocks
JOIN bistore.dbo.models
ON stocks.model = models.model
WHERE stocks.sloc<>'Main'
AND stocks.stock > 0
AND models.mat IN (
IF (@vincome<5000) SELECT DISTINCT mat from models where mat<>'Carbon'
ELSE SELECT DISTINCT mat from models
) /* If income is less than 5000 than chose cheap models , else whatever ) */
**更新**
当客户登录我的门户网站时,我希望为他/她提供最适合他的模型。我将检查他的收入,存储与他关系密切的货物,然后向他提供横幅广告。这是表格中的样本。
DECLARE @vcname VARCHAR(50)
DECLARE @vckids INT
DECLARE @vngng INT
DECLARE @vcweig INT
DECLARE @vcincome INT
DECLARE @Vyear INT
DECLARE @vcost INT
SELECT TOP 1 @vcname = nmsnm,@ vckids = kids,@ vngng = leng,@ vvweig = weig,@ vcincome = income FROM customers ORDER BY id DESC
DECLARE @vmodel VARCHAR(50)
DECLARE @vsloc VARCHAR(50)
SELECT TOP 1 @vmodel = stocks.model,@ vsloc = stocks.sloc,@ vyear = models.year,@ vost = models.cost FROM bistore.dbo.stocks
加入bistore.dbo.models
ON stocks.model = models.model
stocks.sloc&lt;&gt;'Main'
AND stocks.stock&gt; 0
AND models.mat IN(
IF(@ vincome&lt; 5000)从mat&lt;&gt;'Carbon'结束的模型开始选择DISTINCT垫
ELSE BEGIN从模型END中选择DISTINCT垫子
)/ *如果收入低于5000而不是选择便宜的型号,否则无论如何) /
AND models.frames IN(从帧数<48的模型中选择帧/ 选择模型适合长度 /
AND models.type&lt;&gt; '儿童自行车'/ 如果有孩子,选择任何(不大于长度)* /
按NEWID订购()
答案 0 :(得分:1)
您不需要IF
或CASE
,只需要额外的AND
和反向@vincome
支票:
SELECT TOP 1
@vmodel = stocks.model ,
@vsloc = stocks.sloc ,
@vyear = models.year ,
@vcost = models.cost <br>
FROM bistore.dbo.stocks
JOIN bistore.dbo.models
ON stocks.model = models.model
WHERE stocks.sloc <>'Main'
AND stocks.stock > 0
AND ( @vincome >= 5000 OR models.mat <> 'Carbon' )
你看到你甚至不需要子查询。
答案 1 :(得分:0)
在MySQL中,CASE语句的详细信息为here。
可能的用法(请参阅您的对象以获得正确的语法):
SELECT TOP 1 @vmodel = stocks.model , @vsloc = stocks.sloc , @vyear = models.year , @vcost = models.cost <br>FROM bistore.dbo.stocks
JOIN bistore.dbo.models
ON stocks.model = models.model
WHERE stocks.sloc<>'Main'
AND stocks.stock > 0
AND models.mat IN (
CASE sign(@vincome - 5000)
WHEN -1 then (SELECT DISTINCT mat from models where mat<>'Carbon')
ELSE '(SELECT DISTINCT mat from models )
END
) /* If income is less than 5000 than chose cheap models , else whatever ) */
PS:Sign是我用来模仿更大/更小/更小控制的技巧,以便更好地理解CASE语法。