[英]Conditional expression in SQL
I am using MYSQL and PHP. 我正在使用MYSQL和PHP。 I have a table called item.
我有一张桌子,叫做物品。 Two of its attributes are price and discounted price.I have SELECT statement as below:
它的两个属性是价格和折扣价。我有如下的SELECT语句:
$sql =
'SELECT C.cart_id,I.item_id,C.quantity, I.discounted_price,I.price
FROM cart C, item I
WHERE I.item_id = C.item_id';
I want to modify this sql statement and include a conditional expression such that: if discounted_price is 0, it selects price else, discounted_price is selected. 我想修改此sql语句并包括一个条件表达式,例如:如果discounted_price为0,则它选择价格,否则选择了Discounted_price。 Can conditional expression be used in an SQL statement?
可以在SQL语句中使用条件表达式吗? Thanks!
谢谢! :)
:)
Try this: 尝试这个:
SELECT
C.cart_id,
I.item_id,
C.quantity,
COALESCE(I.discounted_price, I.price) AS price
FROM
cart C,
item I
WHERE
I.item_id = C.item_id
COALESCE
selects the first non null value from a list of arguments. COALESCE
从参数列表中选择第一个非空值。 That is, when discount_price is NULL, it returns price. 也就是说,当discount_price为NULL时,它将返回价格。
If your 'null' value is 0.00, you can use this: 如果您的“空”值为0.00,则可以使用以下方法:
SELECT
C.cart_id,
I.item_id,
C.quantity,
IF(I.discounted_price > 0, I.discounted_price, I.price) AS price
...
That is, if discounted price is greater than zero, use that, otherwise use the normal price. 也就是说,如果折价大于零,则使用该价格,否则使用正常价格。
In SQL Server that would be: 在SQL Server中将是:
SELECT C.cart_id,I.item_id,C.quantity, CASE WHEN I.discounted_price IS NULL THEN I.price ELSE I.discounted_price END AS price
FROM cart C, item I
WHERE I.item_id = C.item_id
You could give that a try in mysql. 您可以在mysql中尝试一下。
Something like 就像是
SELECT C.cart_id,I.item_id,C.quantity,
IfNull(I.discounted_price,I.price) as Price
FROM cart C, item I
WHERE I.item_id = C.item_id
Use IsNull if you are using MSSQL 如果使用的是MSSQL,请使用IsNull
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.