I'm trying to select different prices of a product based on the quantity that user chooses.
This is the query I'm working on (it has a syntax error):
select id,
(SELECT
IF(qty_1<='23',price,1)
ELSEIF(('23'>qty_1 && qty_2<='23'),price_2,1)
ELSEIF(('23'>qty_2 && qty_3<='23'),price_3,1)
ELSEIF('23'>qty_3,price_4,1)
END IF) as total
from product;
You have what you have used in stored procedures like this for reference, but they are not intended to be used as you have now. You can use IF as shown by duskwuff. But a Case statement is better for eyes. Like this:
select id,
(
CASE
WHEN qty_1 <= '23' THEN price
WHEN '23' > qty_1 && qty_2 <= '23' THEN price_2
WHEN '23' > qty_2 && qty_3 <= '23' THEN price_3
WHEN '23' > qty_3 THEN price_4
ELSE 1
END) AS total
from product;
This looks cleaner. I suppose you do not require the inner SELECT anyway..
IF() in MySQL is a ternary function, not a control structure -- if the condition in the first argument is true, it returns the second argument; otherwise, it returns the third argument. There is no corresponding ELSEIF() function or END IF keyword.
The closest equivalent to what you've got would be something like:
IF(qty_1<='23', price,
IF('23'>qty_1 && qty_2<='23', price_2,
IF('23'>qty_2 && qty_3<='23', price_3,
IF('23'>qty_3, price_4, 1)
)
)
)
The conditions don't all make sense to me (it looks as though some of them may be inadvertently reversed?), but without knowing what exactly you're trying to accomplish, it's hard for me to fix that.
I found a bug in MySQL 5.1.72 when using the nested if() functions .... the value of column variables (e.g. qty_1) is blank inside the second if(), rendering it useless. Use the following construct instead:
case
when qty_1<='23' then price
when '23'>qty_1 && qty_2<='23' then price_2
when '23'>qty_2 && qty_3<='23' then price_3
when '23'>qty_3 then price_4
else 1
end
For your question :
SELECT id,
IF(qty_1 <= '23', price,
IF(('23' > qty_1 && qty_2 <= '23'), price_2,
IF(('23' > qty_2 && qty_3 <= '23'), price_3,
IF(('23' > qty_2 && qty_3<='23'), price_3,
IF('23' > qty_3, price_4, 1))))) as total
FROM product;
You can use the if - else control structure or the IF function in MySQL.
Reference:
http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/
As per Nawfal's answer, IF statements need to be in a procedure. I found this post that shows a brilliant example of using your script in a procedure while still developing and testing. Basically, you create, call then drop the procedure:
https://gist.github.com/jeremyjarrell/6083251
Related
I've got a case function within my select query. Within this case I want to convert "SongLength" which is in seconds into and mm:ss format with the SEC_TO TIME function. However I get a syntax error upon putting this function in there.
select SongTitle,Artist,SongLength
case
when SongLength < 600 then
sec_to_time(SongLength)
else
sec_to_time(SongLength)
end
from Songs, Artists where Songs.ArtistId = Artists.Id
order by SongTitle;
Try SongLength to make an alias as :
select SongTitle,Artist,
(case
when SongLength < 600 then
sec_to_time(SongLength)
else
sec_to_time(SongLength)
end) as SongLength
from Songs join Artists
on ( Songs.ArtistId = Artists.Id )
order by SongTitle;
see below example works fine
select case
when 400 < 600 then
sec_to_time(400)
else
sec_to_time(300)
end as col
it returns below output
col
00:06:40
So if your datatype of column SongLength is numeric then it should work
http://www.sqlfiddle.com/#!9/835f61/150
Take a look at the following query. How do you display Column 'Action' as text.
If the result of 'Action' is LEQ 0 then dipslay the text "Crash" and if 'Action'
is GRT 0 display the text "Hold"?
SELECT col1 AS Action
FROM vdk
WHERE t_stamp Between "{StartTime}" AND "{EndTime}"
Refactoring the answer above, since i don't see the necessity to add a query to an alias table. I think this should work the other answer should work too btw, but its a little more complicated query for no given reason.
SELECT (CASE WHEN col1 <= 0 THEN 'Crash' ELSE 'Hold' END) AS Action
FROM vdk
WHERE t_stamp Between "{StartTime}" AND "{EndTime}"
Use CASE WHEN ... ELSE ... END and select from your set (query):
SELECT *, (CASE WHEN Action <= 0 THEN 'Crash' ELSE 'Hold' END) as ActionText
FROM (
SELECT col1 AS Action
FROM vdk
WHERE t_stamp Between "{StartTime}" AND "{EndTime}"
) q
This application is similar to my first question and I thought it might help someone else down the the road.
User can select from a Table's Drop Down List a set of options to enter a value into the Database.
Using Ignition's Power Table Component's Extension Function configureEditor with the following script.
This script sets up the Drop Down List.
if colName == 'Action':
return {options': [(0, 'Null'), (1, 'HOLD'), (2, 'CRASH')]}
Along with the same Power Table's Extension Function onCellEdited script.
This script enters the selection as a value into the database.
#onCellEdited Upadte Query
row = rowIndex
col = colIndex
colName = colName
value = newValue
ndx = self.data.getValueAt(row,0)
query = "UPDATE vdk SET %s = ? WHERE ndx = ?" % colName
system.db.runPrepUpdate(query,[value,ndx],'history')
system.db.refresh(self.data)
I want to write a query that will verify 8 parameters of a row are the same as the parameters passed to the procedure. If any one of them is different then modify a status, otherwise do nothing.
Is there a way I can check all those parameters in a single IF case? For example:
IF (v_duty <> duty) OR (v_current <> current) OR (v_frequency <> frequency) THEN
* UPDATE ......;
END IF
Or do I have to use an ELSE IF for each comparison I want to make?
The above doesn't work, with or without brackets between each test.
You could probably manage this with a simple UPDATE and WHERE condition:
UPDATE table_name
SET status_column = 'new_status'
WHERE identifying_column = :identifier
AND (
v_duty != :v_duty
OR v_current != :current
OR v_frequency != :frequency
)
I want set two conditions in query, but query does not work.
SELECT IF((I.num_ip <> '100.100.100.100') &&
(I.num_ip <> '100.100.100.101'), I.num_ip, null) AS num_ip
FROM company C, computers
WHERE C.id_ip = I.id_ip
AND C.date_conn = '2015-08-12'
GROUP BY num_ip
It can be written in other way as well using CASE expression like
Select case when I.num_ip not in ('100.100.100.100', '100.100.100.101')
then I.num_ip else null end) as num_ip
From company C
join computers I on C.id_ip = I.id_ip
Where C.date_conn = '2015-08-12';
** Not sure though why you need a GROUP BY here.
IN your query there are multiple issues
Condition (I.num_ip <> '100.100.100.100') && (I.num_ip <> '100.100.100.101) wont be true almost all the time since num_ip will have value either 100.100.100.100' or '100.100.100.101'
there is one ' missing at end on 101.
please go through "http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html" for detailed use of control flows.
make sure num_ip is nullable.
there are 2 where in query
also if you have group by then you should use aggregate functions COUNT, SUM, AVG, etc. please go through http://www.tutorialspoint.com/mysql/mysql-group-by-clause.htm
Computer table doesn't have alias used as I
Select if(((I.num_ip <> '100.100.100.100') || (I.num_ip <> '100.100.100.101')), I.num_ip, null) as num_ip
From company C, computers I
Where C.id_ip = I.id_ip
and C.date_conn = '2015-08-12'
--Group by num_ip
Thanks,
Tanmay
Your query syntax is invalid, syntax highlighting should warn you.
This one should be correct:
SELECT IF((I.num_ip <> '100.100.100.100') &&
(I.num_ip <> '100.100.100.101'), I.num_ip, null) AS num_ip
FROM company C, computers
WHERE C.id_ip = I.id_ip AND C.date_conn = '2015-08-12'
GROUP BY num_ip
Moreover, computers table is in FROM clause but seems not to be used. Is it normal ?
I am doing a report whereby I can't construct the SQL programatically. I have two values that are fed into the report. The values that can be one of the following three options:
redeem
purchase
redeem AND purchase
The query needs to have a WHERE clause. If "redeem" is fed in, it must have:
... WHERE balance < 0
If "purchase" is fed in, it must have:
... WHERE balance >= 0
if both are fed in, this condition can be left out completely, or it can be said:
... WHERE balance >= 0 OR balance < 0 --> but this is redundant
Is there a way to apply this kind of logic in SQL? Is something like this possible in SQL:
SELECT * FROM account WHERE (if param1 = 'redeem' then 'balance <= 0) ... etc
?
Yep. You're almost there.
WHERE (param='redeem' and balance <=0) or (param='purchase' and balance>=0) or (param='redeem AND purchase ')
Use CASE statements in your WHERE clause. You can find examples here.
I tried the following code in MySQL and it works:
SET #param = 'purchase';
SELECT * FROM TEST.ACCOUNT
WHERE CASE
WHEN #param = 'redeem' THEN BALANCE < 0
WHEN #param = 'purchase' THEN BALANCE >= 0
ELSE TRUE
END;
Would this do the trick?
WHERE
(purchase is not null && balance >= 0)
OR
(redeem is not null && balance < 0)
CASE WHEN param1 = 'redeem' THEN balance <= 0