How can I get the LEAST() value from a SELECT statement? - php

Here's my query:
"UPDATE tbl_pedidos_cotacaos_produtos tb1 LEFT JOIN
tbl_pedidos_produtos tb2 ON tb1.produto_id = tb2.id SET
tb1.status = CASE WHEN tb1.valor_total =
SELECT LEAST(SELECT valor_total FROM tbl_pedidos_cotacaos_produtos WHERE
produto_id = ".$produto->itens[$t]->pedido_id.") THEN 5 ELSE 4 WHERE pedido_id = ".$produto->itens[$t]->pedido_id
Error:
[19-Dec-2015 05:37:48 America/Sao_Paulo] 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 LEAST(SELECT valor_total FROM tbl_pedidos_cotacaos_produtos WHERE produto' at line 1
Apparently I can't use LEAST() with a SELECT statement inside of it.

In MySQL, LEAST() is expecting a number of arguments, and returns the smallest one of those.
What you are getting with your SELECT is however a result set, and therefore I think you are looking for MIN(). Exchange your LEAST() with this and it should do the trick.

Not expert in mysql but you can use this code, to resolve this
SELECT Least(valor_total) FROM tbl_pedidos_cotacaos_produtos WHERE
produto_id = ".$produto->itens[$t]->pedido_id. " instead explicit Least function on a select command :)

Use the MIN() function to find the smallest value across multiple rows.
... total = (SELECT MIN(valor_total) FROM ...)

Related

How to Translate Codeigniter Pre Formatted Query Into an Original Mysql Query (e.g $this->db->select('table1.*,table2.*,table3.*'))

I have a website which is using a CodeIgniter framework and almost using CodeIgniter's preformatted query class in every request to process data from database built by my ex coworker.
One of the example is like this:
function tampilkan_data(){
$this->db->select('barang.*,barang_keluar.*,barang_masuk.*');
$this->db->from('barang');
$this->db->join('barang_keluar', 'barang.id_barang=barang_keluar.id_barang','left');
$this->db->join('barang_masuk', 'barang.id_barang=barang_masuk.id_barang','left');
$this->db->order_by('barang.id_barang','asc');
$this->db->order_by('barang.kode_barang','asc');
$this->db->where('barang.status','0');
return $query = $this->db->get()->result();
}
I want to change the result from that query, but in order to understand it first I have to translate it into an original MySQL query. Attempted to do this:
SELECT `barang`.*, `barang_keluar`.*, `barang_masuk`.*
FROM `barang` AS A
LEFT JOIN `barang_keluar` AS B ON A.id_barang = B.id_barang
LEFT JOIN `barang_masuk` AS C ON A.id_barang = C.id_barang
ORDER BY A.id_barang ASC, A.kode_barang ASC
WHERE A.status = 0
But I got this error
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 'WHERE A.status = 0 LIMIT 0, 25' at line 6
I tried to remove the WHERE A.status = 0 to see which is wrong from my code the I got this error
1051 - Unknown table 'barang'
I thought the problem is in the line SELECT barang.*, barang_keluar.*, barang_masuk.*, because I didn't really know how to write it in an MySQL original formatted.
I already searched for this topic and I even tried to write the query straight to the search bar but I didn't find the right approach according to my case.
Hope someone can help
You can simply print your query, Then you can see your query in original sql format.
function tampilkan_data(){
$this->db->select('barang.*,barang_keluar.*,barang_masuk.*');
$this->db->from('barang');
$this->db->join('barang_keluar', 'barang.id_barang=barang_keluar.id_barang','left');
$this->db->join('barang_masuk', 'barang.id_barang=barang_masuk.id_barang','left');
$this->db->order_by('barang.id_barang','asc');
$this->db->order_by('barang.kode_barang','asc');
$this->db->where('barang.status','0');
$query = $this->db->get()->result(); // notice that i have removed the return keyword
echo $this->db->last_query(); // This will print your query directly on the screen.
}
But the error which you are getting is -> You don't have a table named barang.
Make sure that the table exists.
Hope It Helps...
If you want to look at the query string generated by the CI Query builder then you can log this method $this->db->last_query() which will give the last SQL query as string executed by it.
Your query is almost ok. But you will have to change it on order by. Because u have used asc more than once, that is not supported by mysql as well. You need to modify your query like below
SELECT A.*, B.*, C.*
FROM barang AS A
LEFT JOIN barang_keluar AS B ON A.id_barang = B.id_barang
LEFT JOIN barang_masuk AS C ON A.id_barang = C.id_barang
WHERE A.status = 0 ORDER BY A.id_barang, A.kode_barang ASC
Now be confirm that you have table barang in your database and try again. If you face another sql problem just reply with your screenshot of code snippet here.

#variable mysql return null value on php mysql execution

I have this mysql need to run in php:
$sql_subject_summary = "SELECT
c.subject_code_id, c.subject_name, #total_target:= SUM(s.total_target_question) AS total_target_question,
#total_correct := ROUND((RAND() * (#total_target-10))+10) AS total_correct,
(#total_correct / #total_target)*100 AS percent, c.icon_filename
FROM
edu_subject_code c LEFT JOIN wkp_wg_student_subject s ON c.subject_code_id=s.subject_code_id
WHERE s.student_id=$student_id AND s.week_id = $current_week_id
$sql_inject
GROUP BY s.subject_code_id ";
However, the values of #total_correct, #total_target return null on php mysql execution .
When I run in mysql IDE, then the result is ok.
How to solve this problem?
That's right cause for that to work you need to use SELECT INTO... construct like select col1 into #arg1 from tbl1. Moreover since you are running the query from PHP why you need that at all? if you really need that then consider wrapping the query in a stored procedure and have those parameter as OUT parameter.
Well it's return null cause you are not selecting those parameter. After your query executes, you need to select those parameter saying select #total_correct, #total_target;.
Why don't you just run the query as is (like below) and fetch the specific columns value
SELECT
c.subject_code_id, c.subject_name, SUM(s.total_target_question) AS total_target_question,
ROUND((RAND() * (#total_target-10))+10) AS total_correct,
(#total_correct / #total_target)*100 AS percent, c.icon_filename
FROM
edu_subject_code c LEFT JOIN wkp_wg_student_subject s ON c.subject_code_id=s.subject_code_id
WHERE s.student_id=$student_id AND s.week_id = $current_week_id
$sql_inject
GROUP BY s.subject_code_id

Dynamic SQL Error 804 Incorrect values within SQLDA structure

I'm getting this dynamic sql warning after trying to fetch results from this query:
Warning: ibase_fetch_assoc(): Dynamic SQL Error SQL error code = -804 Incorrect values within SQLDA structure
SELECT VOORRAADAUTO.*, AUTOMERK.*, VOORRAADAUTO.OMSCHRIJVING as uitvoeringnaam
FROM VOORRAADAUTO
LEFT JOIN AUTOMERK ON AUTOMERK.AUTOMERKID = VOORRAADAUTO.AUTOMERKID
WHERE VOORRAADAUTO.SOORTVOORRAADSTATUSID = 2 AND VOORRAADAUTO.TOTAALCONSUMENT > 0 ORDER BY AUTOMERK.OMSCHRIJVING DESC, VOORRAADAUTO.TOTAALCONSUMENT, VOORRAADAUTO.MODELOMSCHRIJVING;
And this php code:
$p_sql = ibase_prepare($sql);
$rs = ibase_execute($p_sql);
while($row = ibase_fetch_assoc($rs)){
$auto = new auto($row);
$this->list[] = $auto;
}
How come there are incorrect values? And how do you solve this problem?
You can always try to run the sql direct on the database.
Because the Sql query looks ok, I can only think maybe there is a typo in a field name or doesn't return rows. Or the where fields aren't numeric
Also may I suggest use alias instead of full table name, that help to read the query.
SELECT V.*, A.*, V.OMSCHRIJVING as uitvoeringnaam
FROM VOORRAADAUTO V
LEFT JOIN AUTOMERK A
ON A.AUTOMERKID = V.AUTOMERKID
WHERE V.SOORTVOORRAADSTATUSID = 2 AND V.TOTAALCONSUMENT > 0
ORDER BY A.OMSCHRIJVING DESC, V.TOTAALCONSUMENT, V.MODELOMSCHRIJVING;
Don't know if you solved it already, but i had the same error with a simple query like:
SELECT * FROM "any_Table" WHERE "id"=1
It worked for me after i replace the * with the column name:
SELECT "id", "Name" FROM "any_table" WHERE "id"=1
I think it has something to do with the interbase driver, i found this:
Bug report
It appears that the php interbase client can't handle boolean fields, after i had changed the boolean field in a integer the select * works.
I'm using XAMPP, PHP Version 5.6.15, with interbase XE7 on windows and used gds32.dll from the interbase install (12.0.4.357).

MySQL query into Code Igniter Active Directory format?

I'm trying to get mysql query into Code Igniter's Active Record syntax but am having a bit of a hard time.
The query is as a result of this question: Multiple mysql ORDER BY's for multidimensional ordering/grouping
I've attempted to format the query myself, have tackled a couple of errors, but am unsure how to progress. I had to add in the get_compiled_select() function to DB_active_rec.php myself and change the _reset_select() from protected to public to get it to run at all.
The suggested query is:
select
t.id,
t.group,
t.date,
t.comlete
from
YourTable t
left join
(select
m.group,
min(m.date) as mindate,
min(t.complete) as groupcomplete
from
YourTable m) mt on mt.group = t.group
order by
coalesce(mt.groupcomplete, t.complete),
coalesce(mt.mindate, t.date),
t.group,
t.complete,
t.date
My translation looks like this (note that there's a 'where' clause not in the original, and that 'date' is actually 'due'):
// Sub query
$this->db->select('m.group, min(m.due) as mindate, min(t.complete) as groupcomplete');
$this->db->from('task m');
$this->db->where('property', $property);
$subquery = $this->db->get_compiled_select();
$this->db->_reset_select();
// Main query
$this->db->select('*');
$this->db->where('property', $property);
$this->db->from('task t');
$this->db->join('($subquery) mt','mt.group = t.group');
$this->db->order_by('coalesce(mt.groupcomplete, t.complete)');
$this->db->order_by('coalesce(mt.mindate, t.due)');
$this->db->order_by('t.group');
$this->db->order_by('t.complete');
$this->db->order_by('t.due');
$query = $this -> db -> get();
// Return
return $query->result();
Unfortunately this is just throwing an 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 'mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.gr' at line 3
The query as reported by CI looks like:
SELECT * FROM (`task` t) JOIN ($subquery) mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.groupcomplete, `t`.`complete)`, coalesce(mt.mindate, `t`.`date)`, `t`.`due`, `t`.`complete`, `t`.`date`
Anyone able to lend some advice as to how to get this formatted correctly? My mysql skills are, unfortunately, pretty bare, so this is pushing my abilities. Much of the approach of my translation is from answers on Stack Overflow, as I have no experience combining queries in this way (with the subquery).
The problem (or 'one of the problems') is here:
$this->db->join('($subquery) mt','mt.group = t.group');
You use single quotes, so the variable $subquery doesn't get expanded.
This can also be seen in the query that is outputted by CodeIgniter.
When you have multiple order by statements u separate them by comma like this
$this->db->order_by('coalesce(mt.groupcomplete, t.complete), coalesce(mt.mindate, t.date), t.due, t.complete, t.date');

Invalid SQL Syntax error

Few weeks ago my code was all fine, but recently I've been unable to load my test database on my web app (built using CakePhp).
This is the error :
Warning (512): SQL Error: 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 ') LEFT JOIN blogs AS Blog ON
(Song.blog_id = Blog.id) WHERE 1 = 1' at line 1
[CORE/cake/libs/model/datasources/dbo_source.php, line 684]
SELECT COUNT(*) AS `count`
FROM `songs` AS `Song`
LEFT JOIN libraries AS `Library` ON (`Song`.`id` = `Library`.`song_id` AND `Library`.`user_id` =)
LEFT JOIN `blogs` AS `Blog` ON (`Song`.`blog_id` = `Blog`.`id`)
WHERE 1 = 1
Warning (512): SQL Error: 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 ') WHERE 1 = 1 ORDER BY Song.postdate
desc LIMIT 100' at line 1
[CORE/cake/libs/model/datasources/dbo_source.php, line 684]
SELECT *, Blog.id
FROM `songs` AS `Song`
LEFT JOIN libraries AS `Library` ON (`Song`.`id` = `Library`.`song_id` AND `Library`.`user_id` =)
WHERE 1 = 1
ORDER BY `Song`.`postdate` DESC
LIMIT 100
You don't have a condition for the Library.userid column:
Library.user_id =)
You need to specify a value on the right side of the equals sign!
your error is here:
Library.user_id =)
maybe you want to change it to:
Library.user_id ='$user_id')
It appears that some value for user_id is not being passed into the query:
`Library`.`user_id` =)
//-----------------^^^^
Likely, there is some PHP variable missing here, or a PDO parameter is not being correctly bound.
SELECT COUNT(*) AS `count` FROM `songs` AS `Song`
left JOIN libraries AS `Library`
ON (`Song`.`id` = `Library`.`song_id` AND `Library`.`user_id` =) <-- HERE's something missing
LEFT JOIN `blogs` AS `Blog` ON (`Song`.`blog_id` = `Blog`.`id`) WHERE 1 = 1
SELECT *,
Blog.id FROM `songs` AS `Song` left JOIN libraries AS `Library`
ON (`Song`.`id` = `Library`.`song_id` AND `Library`.`user_id` =) <-- HERE's something missing
WHERE 1 = 1 ORDER BY `Song`.`postdate` desc LIMIT 100
Since this is a CakePHP question, my answer will approach from the paradigms of the framework. However, given your SQL output, you are either NOT using CakePHP or you are doing something that is definitely a no-no.
Please post the Find statement that you are using the build this SQL statement and your Library's hasMany relationship to Blog. Unless you are using the query method, I think you would get a PHP error before you could build this type of SQL statement using the CakePHP find conventions. If you are using the query method to find your data, then don't. This is a simple query that can be done with CakePHP find easily.
Your library model should like like:
public $hasMany => array('Blog');
And the find:
$this->Library->find(
'all',
array(
'conditions' => array(
'1' => 1 //Not sure why you have Where 1=1
)
'order' => "Library.name DESC",
'limit' => 100
)
);

Categories