简体   繁体   English

MySQL IF语句即时更改值?

[英]MySQL IF Statement change value on the fly?

I'm not even sure if this is quite possible to do with MySQL, but I hope it is. 我甚至不确定这是否可能与MySQL有关,但我希望它是。

OK so i have this SQL command 好的,所以我有这个SQL命令

SELECT * FROM table WHERE $WhereCondition ORDER BY ListStyle

As an example of the data in the ListStyle I might have 作为ListStyle中的数据示例,我可能会有

2000 3000 3700 3800 2000 3000 3700 3800

What I'm hoping to do is use some kind of if statement in the SQL that will allow me to check other fields in a result row so that I can change the value of the ListStyle before I use that in the page to order it appropriately. 我希望做的是在SQL中使用某种if语句,这将允许我检查结果行中的其他字段,以便我可以在我在页面中使用它之前更改ListStyle的值以对其进行适当的排序。

So for instance I have fields a, b and c. 所以例如我有字段a,b和c。 Now if a and b are NOT empty and c = 100 and the ListStyle = 3700, I want to change the value of ListStyle to 3699 so that when I print out a result loop, rows that match the condition ( a != '', b != '', c = 100 and ListStyle = 3700) will then be shown above the rows that have the ListStyle of 3700 现在,如果a和b不为空且c = 100且ListStyle = 3700,我想将ListStyle的值更改为3699,以便在打印出结果循环时,匹配条件的行( a != '', b != '', c = 100 and ListStyle = 3700)将显示在ListStyle为3700的行上方

I can't simply edit the data in the database, even though that would be an easy solution. 我不能简单地编辑数据库中的数据,即使这是一个简单的解决方案。 The data has to stay as it is. 数据必须保持原样。

I originally tried doing this in php. 我最初尝试在PHP中这样做。 While its easy enough to change the value of the ListStyle using if statements, I don't know of an easy way to then actually order my results without sticking everything into an array and then sorting through it. 虽然它很容易使用if语句更改ListStyle的值,但我不知道一种简单的方法,然后实际排序我的结果,而不是将所有内容都插入到数组中然后对其进行排序。 I really don't want to do that as it would mean re-writing a lot of code, which is why I'm hoping this is all possible to do in MySQL. 我真的不想这样做,因为它意味着重写了很多代码,这就是为什么我希望这在MySQL中都可以做到。

Can anyone help with this? 有人能帮忙吗?

try something like: 尝试类似的东西:

SELECT * FROM table_name WHERE $WhereCondition ORDER BY CASE 
        WHEN ( a = 0, b = 0, c = 100 and ListStyle = 3700)  THEN 1
        WHEN ( a = 10, b = 20, c = 200 and ListStyle = 3400) THEN 2
        ELSE 10
    END

You can use IF or CASE inside the ORDER BY statement like 您可以在ORDER BY语句中使用IFCASE

...
ORDER BY
  IF(condition1, then_value, else_value)

How about this? 这个怎么样?

SELECT a,b,c, IF($condition, 3700, 3699) AS order WHERE $whereCondition ORDER BY order

Expressing $condition in MySQL might be tedious, but I think it's possible. 在MySQL中表达$ condition可能很乏味,但我认为这是可能的。

你可以使用触发器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM