get value from subquery in CodeIgniter - php

the thing is that i don know if there is a way to get a value from a subquery over an update operation, the query that i'm trying to do looks like this, on a example code of my model :
$query = "UPDATE some_table SET value_1 = ((SELECT value_2 FROM other_table WHERE id = 2) + 1) WHERE id = 2";
$this->db->query($query);
i hope you can help me or at least let me know an alternative way to get this using the active record
PD i'm working with the CodeIgniter Framework

The equivalent of
UPDATE some_table SET value_1 = ((SELECT value_2 FROM other_table WHERE id = 2) + 1) WHERE id = 2
in ActiveRecord is probably:
$value_2 = $this->db->get_where('other_table', array('id' => 2))[0];
$data = array('value_1', $value_2 + 1);
$this->db->update('some_table', $data, array('id' => 2));

I not working with Codeigniter, but try this:
$query = "UPDATE some_table st SET st.value_1 = ((SELECT ot.value_2 FROM other_table ot WHERE ot.id = 2) + 1) WHERE st.id = 2";
$this->db->query($query);

Related

Mysql query failed to execute

Why this code does not work in the database?
$sql =
UPDATE users_information INNER JOIN users ON users.id = user_id SET following_count = :following_count WHERE user_id = :user_id;
$data :
["following_count" => "following_count + 1" , "user_id" => "1273"]
execute return false
following_count + 1 is expression, You cannot bind expressions, only values. So, rewrite your query as:
$sql = "
UPDATE users_information INNER JOIN users ON users.id = user_id
SET following_count = following_count + 1
WHERE user_id = :user_id";
And in $data you pass only user_id:
$data = ["user_id" => "1273"];
Also, it's unclear to me what's the point of using join, why not simple query:
$sql = "
UPDATE users_information
SET following_count = following_count + 1
WHERE user_id = :user_id";
["following_count" => "following_count + 1" , "user_id" => "1273"] .
Here "following_count + 1" its a string .
Make it Integer. Or if its a string then in database change the type
as varchar.
data should be like the following:
$following_count = $following_count + 1;
["following_count" => "some_number(from following_count value)" , "user_id" => "1273"]

User defined variable not working in Mysql Code Igniter

I am trying to rank the rows based on when was it lasted updated partitioned by category name.
$query = "SELECT
category_name,
topic_title,
updated_ts,
#topic_rank := IF(#current_category = category_name, #topic_rank + 1, 1) AS topic_rank,
#current_category := category_name AS current_category
FROM topic_master
ORDER BY category_name, updated_ts DESC
";
$data = $this->db->query($query);
if($this->db->affected_rows() > 0)
{
return $data;
}
else
{
return false;
}
This query runs perfectly fine in MySQL and gives me the topic_rank as 1,2,3 and so on.
When I run this in CodeIgniter, I get topic_rank as 1 for all records.
What could be the issue ?
Try to use codeigniger database methods result_array():
$q = $this->db->query($query);
$data = $q->result_array();
Found an alternate way to solve this problem. No idea why the user defined variable was not working.
select category_name, topic_title as last_topic, updated_ts as last_activity, topic_pri_key as last_topic_id from
(
select
a.category_name, a.topic_title,
a.updated_ts,
a.topic_pri_key,
count(b.updated_ts)+1 as rank
from
topic_master a
left join
topic_master b
on a.updated_ts < b.updated_ts and a.category_name = b.category_name
group by 1,2,3,4
) a
where rank = 1

Count and Join did not work on phalcon framework

I have the code like this
$phql = "SELECT COUNT(a.id) FROM UserParkingIn a JOIN UserVehicle b ON a.userVehicleId = b.id WHERE b.vehicleTypeId = 1";
$result = $this->modelsManager->executeQuery($phql);
echo $result;
in UserParkingIn Table I have example id = 10, userVehicleId = 2
in UserVehicle Table I have example id =10, userVehicleId = 2, vehicleTypeId = 1
It return empty, but when I execute this query in phpMyAdmin I use this sql logic it return right number.
SELECT COUNT(a.id) FROM user_parking_in a JOIN user_vehicle b ON a.userVehicleId = b.id WHERE b.vehicleTypeId=1;
and it return number 7
Can someone explain why this return error?
Thank you.
I found the solution that id I used to count must set an alias to be like quota like this.
$query = $this->modelsManager->createQuery("SELECT COUNT(a.id) as quota FROM UserParkingIn a JOIN UserVehicle b ON a.userVehicleId = b.id WHERE a.ospoId = '$ospoId' ");
$records = $query->execute();
foreach($records as $record){
$parkingUsed = $record->quota;
}
and now it is working.

Joining two tables to get a count

I am attempting to count comments on a particular page with the following problematic sql query:
$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND page_id = '943'"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;
the problem is it is outputting 0 and not 2.
The tables are as follows:
pages:
id:1 page_id:943
id:2 page_id:978
id:3 page_id:977
comments:
id:2 page_id:1 "hello"
id:3 page_id:1 "great"
id:4 page_id:3 "super"
So really the original query should be getting each comment's true page_id from the page_id as set in the pages tables, as joined by comments.page_id = pages.id
What would the final code look like to either make that join, and/or get that count? Thank you.
Try:
SELECT c.* FROM `comments` c
JOIN `pages` p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'
"SELECT * FROM comments, pages WHERE comments.page_id = pages.id AND is_approved = '1' AND comments.page_id = '943'"
Try using:
SELECT count(*) as cnt
FROM `comments` c join pages p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'
It seems like a very poor database design to have two columns with the same name in different tables that mean different things. You should probably change the name of pages.page_id to something else.
And, this returns the count directly, so you can read the value from the row. If you just want the count, there is no reason to return all the matching rows.
no join is needed:
$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;
ofcourse i would suggest a count statement if you do not need/use the data:
$query = "SELECT COUNT(*) as total FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$total = $row['total'];
echo $total;

MYSQL Count Method

function sum($nomId){
$sql = "SELECT SUM(nomDetCantidad) FROM table2 where Id = $nomId";
$Resultado=$this->ProcesaSQLQueryList($sql);
if($Resultado>0){
foreach($Resultado as $key => $valor){
$cantidadTotal = $valor[0];
}
}
if($Resultado=='null'){$cantidadTotal=0;}
$sql = "UPDATE table1 SET nomCantidadTotal=$cantidadTotal,nomActualizado = NOW() WHERE nomId= $nomId";
return $this->ProcesaSQLQueryUpdate($sql);
and this is the function I call
function ProcesaSQLQueryList($SQLQuery){
$row= array();
if(!$this->link_mysql) $this->link_mysql = conectarManager();
if($res = mysql_query($SQLQuery,$this->link_mysql)){
while($r = mysql_fetch_array($res)){
$row[] = $r;
}
mysql_free_result($res);
return $row;
}else{
$this->last_error = $SQLQuery . " - " . mysql_error();
return -1;
}
}
So I sum up whatever I have in a field table 2 with the foreign key of table 1 then my result gets updated to the table 1 field but if I delete the fields in table 2 result wont get updated to 0 any suggestions I'm pretty sure this is an easy one but can't seem to find it
$sql = "SELECT SUM(nomDetCantidad) FROM table2 where nominaId = $nomId";
$Resultado = $this->ProcesaSQLQueryList($sql);
if ($Resultado > 0) {
foreach ($Resultado as $key => $valor) {
$cantidadTotal = $valor[0];
}
}
if ($cantidadTotal == '') {
$cantidadTotal=0.00;
}
$sql = "UPDATE table1 SET nomCantidadTotal=$cantidadTotal,nomActualizado = NOW() WHERE nomId = $nomId";
return $this->ProcesaSQLQueryUpdate($sql);
There! It was sending me a blank variable xD but fixed and there are more suitable ways to do it, I agree with Spencer but if a client wants a red swing he has to get a red swing you know? :) thanks for the help guys!
If you need a zero returned when there are no "matching" rows in table2, then wrap the return expression in an IFNULL function.
SELECT IFNULL(SUM(nomDetCantidad),0) FROM table2 ...
You could significantly reduce the amount of code you have, reduce the number of roundtrips to the database, and improve performance by doing all this work in a single UPDATE statement. You can use either a correlated subquery or an OUTER JOIN:
-- using a correleated subquery
UPDATE table t1
SET t1.nomActualizado = NOW()
, t1.nomCantidadTotal =
( SELECT IFNULL(SUM(t2.nomDetCantidad),0) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = t1.nomID
)
WHERE t1.nomId = $nomId
-- using an OUTER JOIN
UPDATE table1 t1
LEFT
JOIN (SELECT t2.Id, SUM(t2.nomDetCantidad) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = $nomId
GROUP BY t2.Id
) s
ON s.Id = t1.nomID
SET t1.nomCantidadTotal = IFNULL(s.nomCantidadTotal,0)
, t1.nomActualizado = NOW()
WHERE t1.nomID = $nomId
It's not at all clear why you need to store this total on table1, when you could derive it from table2 whenever you need it, without storing that value on table1 at all...
SELECT t1.nomId
, IFNULL((SELECT SUM(t2.nomDetCantidad) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = t1.nomID
),0) AS nomCantidadTotal
FROM table1 t1
WHERE t1.nomId = $nomId

Categories