SQL query with CASE in SELECT doesn't work - php

I have this part of a larger complex query:
SELECT SUM(pir.priceChange) AS CASE
WHEN (SUM(pir.priceChange) > 0) THEN sellSum
WHEN (SUM(pir.priceChange) < 0) THEN priceSum
END
Whenever I try to pass it on to MySQL (MyISAM) via PDO, it throws me an exception:
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT SUM(pir.priceChange) AS CASE WHEN (SUM(pir.priceChange) > 0) THEN sellSu' at line 17
I imagine it has something to do with the fact that I'm trying to use a CASE statement incorrectly. Would really like to know what's exactly wrong, thanks in advance.
EDIT: My full query (edited without any cases):
SELECT pi.id AS id,
pi.type AS type,
pi.parValue AS rating,
pi.duration AS time,
countAmt.amt AS amtSold,
IFNULL(pii.pChange,
0) AS priceTotal,
0) AS costTotal,
IFNULL(pii.selfPrice,
0) AS costPrice,
(IFNULL(pii.sellSum,
0) - IFNULL(pii.selfPrice,
0)) AS profit,
countClose.amtClosed AS amtClosed
FROM salon.paymentInstrument as pi
(SELECT SUM(pir.priceChange) AS pChange,
SUM(pir.costChange) AS cChange,
(IFNULL(pir.priceChange,
0) - IFNULL(pir.costChange,
0)) AS selfPrice,
pii.paymentInstrumentID
FROM salon.paymentInstrumentRegister as pir
JOIN salon.paymentInstrumentItem as pii ON pir.paymentInstrumentItemID = pii.id
WHERE pir.date >= '2014-04-11'
AND pir.date <= '2014-04-25'
GROUP BY pii.paymentInstrumentID
) as pii
(SELECT pii.paymentInstrumentID,
COUNT(*) AS amtClosed
FROM salon.paymentInstrumentItem as pii
WHERE pii.annulTime >= 2014-04-11
AND pii.annulTime <= 2014-04-25
AND pii.status <> "active"
GROUP BY pii.paymentInstrumentID
) as countClose
(SELECT pii.paymentInstrumentID,
COUNT(*) AS amt
FROM salon.paymentInstrumentItem as pii
WHERE pii.startTime >= 2014-04-11
AND pii.startTime <= 2014-04-25
GROUP BY pii.paymentInstrumentID
) as countAmt
Sorry for improper formatting, it's generated dynamically with PHP. I have a feeling i'm making a mistake somewhere else in the query.

Try this way:
SELECT CASE WHEN SUM(pir.priceChange)>0 THEN SUM(pir.priceChange) END as SumPrice,
CASE WHEN SUM(pir.priceChange)<0 THEN SUM(pir.priceChange) END as priceSum
FROM TableName
An example in SQL Fiddle.

Try this:
SELECT CASE
WHEN (SUM(pir.priceChange) > 0) THEN sellSum
WHEN (SUM(pir.priceChange) < 0) THEN priceSum
END

Related

SQL Variable inside PHP Statement

My code:
$sql = "SET #row_number = 0; SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '".$data[2]."' OR o = '".$data[4]."' ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
$result = mysql_query($sql) or die(mysql_error());
The error:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'SELECT (#row_number:=#row_number + 1) AS num, player,
reinforcees, reinforcers F' at line 1
When I echo the SQL statement, I get the following: SET #row_number = 0; SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '1' OR o = '5' ORDER BY CASE WHEN player = '2' THEN 1 ELSE 2 END
When I run that echod statement through phpMyAdmin, it runs successfully, and gives me rows of results.
But why doesn't it work in a PHP statement? What's going on? How do I get PHP to do what SQL is doing?
And before anyone says I haven't tried to find the answer myself, if you Google "sql variable" php site:stackoverflow.com, every question I find is about accessing SQL results in PHP (i.e., loops) or inserting PHP variables in SQL, which is not what I need. I'm trying to insert an SQL variable into the SQL statement.
Also: I realize I should stop using MySQL, and am in the process of converting, but in order to quickly resolve a bug...I'm using MySQL.
mysql_query doesn't support multiple queries in one call. You would need to upgrade to mysqli or PDO to enable that. In the meantime though, you can implement what you want in a single query using a CROSS JOIN to initialise the row_number variable e.g.
$sql = "SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers
FROM _KoT_villages
CROSS JOIN (SELECT #row_number := 0) r
WHERE o = '".$data[2]."' OR o = '".$data[4]."'
ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
The MySQL client in php expects individual statements
Open MySQL client
First Statement:
SET #row_number = 0
2nd Statement:
SELECT
(#row_number:=#row_number + 1) AS num,
player,
reinforcees,
reinforcers
FROM
_KoT_villages
WHERE
o = '".$data[2]."'
OR o = '".$data[4]."'
ORDER BY
CASE WHEN player = '".$user_class->id."' THEN 1
ELSE 2
END
$result = mysql_query( [2nd Statement] ) or die(mysql_error());
Close MySQL client

WHERE NOT IN AND WHERE error

I tried moving the WHERE clause many times but I'm still having an error. Am I doing the WHERE NOT IN AND WHERE clause wrong? The code is working perfectly fine until I added the WHERE ha_rooms.deleted != 1 clause. I also tried using deleted <> 1 but it still shows the same error
$query2 = $this->db->query("SELECT * FROM ha_rooms
WHERE ha_rooms.deleted != 1 JOIN ha_user_room_merged
WHERE ha_rooms.room_id NOT IN (SELECT ha_user_room_merged.room_id
FROM ha_user_room_merged WHERE ha_user_room_merged.deleted = 0)
group by ha_rooms.room_id");
The error is this
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN ha_user_room_merged WHERE ha_rooms.room_id NOT IN (SELECT
ha_user_room_merg' at line 1
If I said frankly, your query is not done properly in anyway but it gives pretty much clear vision of what you are trying to do if you don't have any other logic behind that. So, I would like to suggest you to do google for SQL Syntax, Ordering, use of GROUP BY, WHERE sub-query etc. BTW below is the proper version of your query please check if it's useful for you
SELECT hr.*
FROM ha_rooms hr
JOIN ha_user_room_merged hurm On hurm.room_id = hr.room_id
WHERE hurm.deleted = 0
AND hr.deleted <> 1
Use below codeigniter query. in your join there is no ON
$all_ids = 0;
$this->db->select('group_concat(room_id) as ids');
$this->db->where('deleted', 0);
$ids = $this->db->get('ha_user_room_merged')->row_array();
if($ids) {
$all_ids = explode(',', $ids['ids']);
}
$this->db->where('hr.deleted !=', 1);
$this->db->where_not_in('hr.room_id', $all_ids);
$this->db->join('ha_user_room_merged hrm', 'hrm.room_id = hr.room_id');
$this->db->group_by('hr.room_id');
$this->db->get('ha_rooms hr')->result_array();
Please try..
select * from ha_rooms as a inner join ha_user_room_merged b on a.ha_rooms.id = b.room_id
where b.deleted <> 0
Output
ha_rooms.room_id ha_user_room_merged.room_id deleted
1 1 1
2 2 1
3 3 1
4 4 1
Thanks :)

mysql query error in PHP but working in phpmyadmin

I have write a query in mysql and it is running in phpmyadmin, but in PHP it giving me error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select docno, docdate, doctype, narration, drcr, (case when drcr = 'Dr' then amo' at line 2
My Query is in PHP is :
$sql = "set #runtot := 0; select docno, docdate, doctype, narration, drcr, (case when drcr = 'Dr'
then amount else 0 end) as debit, (case when drcr = 'Cr' then amount else 0 end) as
credit, concat(abs((#runtot := #runtot + (case when drcr = 'Dr' then amount else amount*-1
end))), (case when #runtot < 0 then ' Cr' else ' Dr' end) ) as balance from (select docno,
docdate, doctype, narration, amount, drcr from ledger where accode = 1 )as q1";
what is wrong here with php?
You have to use transactions to perform several commands in MySQL.
You create a varible first and then execute another command.
Using just single function mysqli_query you can perform only one command and commands are separated by ;.
When you paste the code into PHPMyAdmin, it will work though as it is still supposed to be a transaction.
You can read more about transactions.

MYsql query and DB help

When trying to execute this query my mysql server cpu usage goes to 100% and the page just stalls. I setup an index on (Client_Code, Date_Time, Time_Stamp, Activity_Code, Employee_Name, ID_Transaction) it doesn't seem to help. What steps can I go about next to fix this issue? Also there is already one index on the database if that matters any. Thanks
> $sql = "SELECT m.Employee_Name, count(m.ID_Transaction)
>FROM ( SELECT DISTINCT Client_Code FROM Transaction)
> md JOIN Transaction m ON
> m.ID_Transaction = ( SELECT
> ID_Transaction FROM Transaction mi
> WHERE mi.Client_Code = md.Client_Code AND Date_Time=CURdate() AND Time_Stamp!='' AND
> Activity_Code!='000001'
> ORDER BY m.Employee_Name DESC, mi.Client_Code DESC, mi.Date_Time DESC,
> mi.ID_Transaction DESC LIMIT 1 )
> group by m.Employee_Name";
I've got a feeling it's due to that > sign next to the AND, what is the expression you're trying to make with that?
Could you express in plain English what results you're after with your query? I've got a feeling this query can be rewritten; that might fix your performance issue. A double join on itself might hurt performance badly.
Something like "the number of transactions per employee for today"?
If that's what you're after, please try this and refine from there:
select m.Employee_Name, count(m.ID_Transaction)
from Transaction m
where m.Date_time=CURdate()
and m.Time_Stamp != ''
and m.Activity_Code != '000001'
group by m.Employee_Name
I Could've sworn I had already posted my response here today....
Why not use a double GROUP BY? I think this is what you were looking for...
SELECT Employee_Name, count(ID_Transaction) FROM Transaction WHERE Date_time=CURdate() AND Time_Stamp != '' AND Activity_Code != '000001' GROUP BY Client_Code, Employee_Name

Setting an error limit while updating table based conditions php

I have got a question. I have not done this before and am not sure if that is how it should be done.
I have a mySQL query which is working correctly. I use it in phpMyAdmin query editor whenever I want to do an update. However, I want to make life easier for a user by putting the query in a php script so the user can just click a link and the task is done.
I did the following:
$sql = " SET #error_limit = 10E-6;
UPDATE (
SELECT r.rmc_id, 'rmc_raw_data' src, r.rmc_time, r.rmc_date, r.latitude, r.longitude,
IF(s.server_id IS NULL, 'Mobile', 'Both') c FROM rmc_raw_data r
LEFT JOIN server_log_data s
ON r.rmc_time = s.server_rmc_time AND r.rmc_date = s.server_rmc_date AND ABS(r.latitude - s.server_latitude)/r.latitude < #error_limit AND ABS(r.longitude - s.server_longitude)/r.longitude < #error_limit
UNION
SELECT s.server_id, 'server_log_data' src, s.server_rmc_time, s.server_rmc_date, s.server_latitude, s.server_longitude, IF(r.rmc_id IS NULL, 'Server', 'Both') c FROM rmc_raw_data r
RIGHT JOIN server_log_data s
ON r.rmc_time = s.server_rmc_time AND r.rmc_date = s.server_rmc_date AND ABS(r.latitude - s.server_latitude)/r.latitude < #error_limit AND ABS(r.longitude - s.server_longitude)/r.longitude < #error_limit
) t
LEFT JOIN rmc_raw_data r1
ON r1.rmc_id = t.rmc_id AND t.src = 'rmc_raw_data'
LEFT JOIN server_log_data s1
ON s1.server_id = t.rmc_id AND t.src = 'server_log_data'
SET
r1.data_source = c, s1.data_source = c;";
$result = mysql_query($sql, $link);
if($result){
echo " Query executed successfully";
...
...
So I put the whole thing my php script but got a mysql error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE ( SELECT r.rmc_id, 'rmc_raw_data' src, r.rmc_time, r.rmc_date, r.latit' at line 1
Could someone suggest what am doing wrong here? It is my thinking that the error limit I have set on the first line of the query is responsible but I had thought that one could put his working query in the mysql_query() and it works.
'rmc_raw_data' src, this quotes will break the query ???

Categories