Sub queries in Yii - mysql

I have the following mysql query which works well in phpmyadmin when i execute it :
"SELECT * FROM accounts_users WHERE id = ( SELECT teacher_id FROM general_teacher_student_associations WHERE student_id = 509 )";
But when i execute via Yii, it breaks :
$query = "SELECT * FROM accounts_users WHERE id = ( SELECT teacher_id FROM general_teacher_student_associations WHERE student_id =509 )";
$command = Yii::app()->db->createCommand($query);
$teachers_list = $command->query();
return $teachers_list;
509 is a dynamically fetched value.
1. What am i doing wrong?
2. Can this be done in a better way?
/******Edited***********/
Found the error : The sub query returns more than one row. Can i use single query to fetch all the values other than using a foreach loop and then inside that executing another query?
Solution : (Accepting Daniels answer since his comment actually solved the issue)
$query = "SELECT * FROM accounts_users WHERE id IN ( SELECT teacher_id FROM general_teacher_student_associations WHERE student_id =509 )";
$command = Yii::app()->db->createCommand($query);
$teachers_list = $command->queryAll();
return $teachers_list;
p.s: This is an edition work and i am not allowed to touch model and hence using model relations is out of window and thats why i ended up with this

Try:
$teachers_list = Yii::app()->db->createCommand()->select('ausers.*')
->from('accounts_users ausers')
->join('( SELECT teacher_id FROM general_teacher_student_associations WHERE student_id = 509 ) as teachers ON teachers.teacher_id = ausers.id')
->queryRow();

Related

How get a value from mysql in prestashop?

I want to get a value from a table like that:
SELECT id_image FROM `ps_image` WHERE id_product = 903 limit 1
How can i integrate this sql command in prestashop?
$product_id = '903';
$query = Db:: getInstance()->getRow(
'SELECT id_image FROM '._ DB_PREFIX_.'image WHERE id_product ='. $product_id
);
Use $query variable to get id of image.

how to get latest date from two conditions?

I have drop down where the drop down is list of namaJabatan
my table - infojawatan
ID - PK of the table
namaJabatan - where the condition appear ($search - its up to where the user select from Dropdown)
tarikhKemaskini - where i want to get the latest date of row
my query
$sql = "SELECT * FROM infojawatan WHERE namaJabatan = '$search' && tarikh Kemaskini IN (SELECT MAX(tarikhKemaskini) FROM infojawatan GROUP BY ID)";
$sql_rs = mysql_query($sql);
while($row_Sql = mysql_fetch_array($sql_rs)) {
$tarikhKemaskini = $row_Sql['tarikhKemaskini'];
}
echo "Current Date :" .$tarikhKemaskini;
You have a few syntax errors in your SQL.
SQL spells out AND, not &&.
tarikhKemaskini is one word.
SELECT *
FROM infojawatan
WHERE namaJabatan = :namaJabatan AND
tarikhKemaskini IN (
SELECT MAX(tarikhKemaskini)
FROM infojawatan
GROUP BY ID
)
Note carefully that I used :namaJabatan there instead of hard coding $search. Hard coding variables into SQL leaves you open to a SQL Injection Attack where a malicious attacker can craft a search query that lets them get more information than they're allowed to, or even run arbitrary SQL queries.
Instead, use parameters, the :namaJabatan there, and pass your variables in when you execute the query.
Unfortunately the mysql_query interface doesn't support this. Fortunately it was deprecated and there are now better interfaces. Here's a breakdown. I'd recommend using PDO as it is a generic interface applicable to any SQL database. Then you can use the more secure and efficient prepared statements with bind parameters.
$stmt = $dbh->prepare("
SELECT *
FROM infojawatan
WHERE namaJabatan = :namaJabatan AND
tarikhKemaskini IN (
SELECT MAX(tarikhKemaskini)
FROM infojawatan
GROUP BY ID
)
")
$stmt->execute(array( ':namaJabatan' => $search));
while( $row = $stmt->fetch() ) {
echo $row['tarikhKemaskini'];
}

How can I execute this SQL query in Drupal?

I'd like to execute the following SQL query in Drupal...but haven't had any luck.
SELECT SUM(field_count) FROM headon_entry WHERE uid = 1 AND tid = 263;
I've used the following, but with no luck:
$query = db_select('headon_entry', 'he')
->condition('uid', $uid)
->condition('tid', $product_id);
$query->addExpression('SUM(field_count)', 'field_count');
$entry_quantity = $query->execute();
Your query comes out as
SELECT SUM(field_count) AS field_count
FROM
{headon_entry} he
WHERE (uid = :db_condition_placeholder_0) AND (tid = :db_condition_placeholder_1)
So what you've got is correct as far as building the query goes.
What you haven't done is extract the result from the query execution. Try this:
$entry_quantity = $query->execute()->fetchField();

Zend Framework 2 - sql subquery

I'm trying to run a special SQL query in ZF 2.
SELECT listingId, COUNT(*) as num
FROM
(SELECT DISTINCT listingId, locationId
FROM l_f_locations
WHERE locationId IN ( 7, 9, 10)) AS foo
GROUP by listingId, HAVING num = 3
I tried creating the subquery first as it's a complete MySQL query but then fail to integrate it into the main query at all. I can't alias the subquery e.g. "AS foo" as this is a requirement for the complete SQL squery to work.
Any ideas?
First of all, you can do this without a sub-query:
SELECT listingId, COUNT(DISTINCT locationId) AS num
FROM l_f_locations
WHERE listingId IN(7,9,10)
GROUP BY listingId
HAVING num = 3;
For future reference, however, you could do the query you mention using a pair of Zend_Db_Select objects, one for the sub-query and another for the main:
$subQuery = $dbAdapter->select()
->from('l_f_locations', array('listingId', 'locationId'))
->where('locationId IN(7,9,10)')
->group('listingId')
->group('locationId');
$select = $dbAdapter->select()
->from($subQuery, array('*', 'num' => 'COUNT(*)'))
->group('listingId')
->having('num = 3');
$result = $select->query()->fetchAll();

Executing an update statement with a select subquery clause in C

I have the following sql that I run in C:
snprintf(sql, 200, "update rec set name = (select name from pers where id = %d )
where id = %d",rec_id , emp_id );
mysql_query(conn, sql) returns a successful result but it's putting 1 in the "rec" table in the "name" field instead of the name, but when I printf the output and use it in MySQL it's working fine.
update rec set name = (select name from pers where id = 104 ) where id = 43
Is there something wrong with my sprintf? Or something has to be added?
I also tried static sql command like this
snprintf(sql,"update rec set name = (select name from pers where id = 104 ) where id = 43");
and it also put 1 in the rec.name
Is that due to count of record returned by the sub query? Can you verify by putting a condition which returns e.g. 2 records so that the name is set to 2? if this is the reason then (though less performing approach) try splitting the queries and see if it works this time.