change SQL query from PHP - php

How do I change a certain SQL query form inside PHP code Like for example here in the below code
<?php
function eb_mine_views_query_alter(&$view, &$query) {
if ($view->name == 'statuser') {
dsm($query, 'before');
$query->where[0]['type'] = 'OR';
dsm($query, 'after');
}
}
?>
this code is related to a Drupal modification.
previous query
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM
{node} node
INNER JOIN {taxonomy_index} taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = :views_join_condition_0
INNER JOIN {taxonomy_index} taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = :views_join_condition_1
WHERE ((( (taxonomy_index_value_0.tid = :db_condition_placeholder_2) )**AND**( (taxonomy_index_value_1.tid = :db_condition_placeholder_3) )))
ORDER BY node_created DESC
After the above code runs the resulting query
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created FROM node node OUTER JOIN taxonomy_index taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '9' OUTER JOIN taxonomy_index taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '6' WHERE ((( (taxonomy_index_value_0.tid = '9') )OR( (taxonomy_index_value_1.tid = '6') ))) ORDER BY node_created DESC LIMIT 5 OFFSET 0;
As you can see the query changed from AND to OR.
Now I want to change the same code like this:
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created FROM node node LEFT OUTER JOIN taxonomy_index taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '9' LEFT OUTER JOIN taxonomy_index taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '6' WHERE ((( (taxonomy_index_value_0.tid = '9') )OR( (taxonomy_index_value_1.tid = '6') ))) ORDER BY node_created DESC LIMIT 5 OFFSET 0;
rather than using OUTER JOIN I want to use LEFT OUTER JOIN. So how do I do this in my PHP code

Try this:
<?php
function eb_mine_views_query_alter(&$view, &$query) {
if ($view->name == 'statuser') {
dsm($query, 'before');
$query->where[0]['type'] = 'OR';
$query->tables[1]['type'] = 'LEFT OUTER';
dsm($query, 'after');
}
}
?>

Related

php mysql while loop query optimization

I have php/mysql script running which is like this:
$sql = "select a.column1 from table1 a";
$query = mysql_query($sql);
while ($fec = mysql_fetch_assoc($query)) {
$sub1 = "select column1,column2 from subtable1 where id=" . $fec['a.column1'];
$subquery1 = mysql_query($sub1);
while ($subfec1 = mysql_fetch_assoc($subquery1)) {
//all data .....
}
$sub1 = "select column1,column2 from subtable2 where id=" . $fec['a.column1'];
$subquery2 = mysql_query($sub2);
while ($subfec2 = mysql_fetch_assoc($subquery2)) {
//all data .....
}
$sub2 = "select column1,column2 from subtable3 where id=" . $fec['a.column1'];
$subquery3 = mysql_query($sub3);
while ($subfec3 = mysql_fetch_assoc($subquery3)) {
//all data .....
}
}
Now I've many many many records in table1, subtable1, subtable2 and subtable3. And problem is that it takes around 7 hours to display the results. Moreover the CPU Usage is 100%
Please suggest the optimization tips to overcome this issue.
Use a single query to get all records
SELECT
a.column1,
s.column1,
s.column2,
s2.column1,
s2.column2,
s3.column1,
s3.column2
FROM table1 a
LEFT JOIN subtable1 s ON s.id = a.column1
LEFT JOIN subtable2 s2 ON s.id = a.column1
LEFT JOIN subtable3 s3 ON s.id = a.column1
Here
$sql="
SELECT
a.column1 acolumn1,
s.column1 scolumn1,
s.column2 scolumn2,
s2.column1 s2column1,
s2.column2 s2column2,
s3.column1 s3column1,
s3.column2 s3column2
FROM table1 a
LEFT JOIN subtable1 s ON s.id = a.column1
LEFT JOIN subtable2 s2 ON s.id = a.column1
LEFT JOIN subtable3 s3 ON s.id = a.column1";
$query=mysql_query($sql);
while ($fec=mysql_fetch_assoc($query)) {
// display any info here
}
Use aliases for accessing different table columns

query error php codeigniter

this my query
function get_transaksi_by_tgl($tgl_awal,$tgl_akhir,$limit, $offset = 0) {
$rs['query'] = $this->db->query("SELECT a.id_transaksi, a.nama, a.tgl_transaksi,
(SELECT COUNT( id_transaksi ) AS jum FROM tbl_detail_trs_menu WHERE id_transaksi = a.id_transaksi)
AS jumlah, a.status_transaksi, a.total, b.status_pelanggan, c.nama_karyawan FROM tbl_transaksi a
LEFT JOIN tbl_pelanggan b ON a.id_pelanggan = b.id_pelanggan LEFT JOIN tbl_karyawan c
ON a.id_karyawan = c.id_karyawan WHERE a.status_transaksi = 'OK' AND a.tgl_transaksi between ".$tgl_awal."
AND ".$tgl_akhir." LIMIT ".$offset.",".$limit."");
echo "jumlah : ".$rs['query']->num_rows();
return $rs;
}
but this query can't return rows....
whereas i try query in database can return 4 row... why??? thx u

Drupal 7 WHERE using OR and AND

Writing a custom module trying to look up comments. I have a SQL statement as follows:
$client_comment = db_query("SELECT comment.subject AS comment_subject,
comment.cid AS cid,
comment.nid AS comment_nid,
comment.created AS comment_created
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
INNER JOIN {field_data_field_associated_client} associated_client ON comment.cid = associated_client.entity_id
WHERE (( (associated_client.field_associated_client_nid = '$nid')
OR (comment.nid = '$nid') )
AND (comment.status <> '0')
AND (node_comment.status = '1') )
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0");
Ideally, this is supposed to return the following:
However, I get the following:
For some reason, it is only returning the "associated_client" result instead of the "comment.nid" result. Here is the full statement I'd like to get working. I know it's a SMH moment, but any help would be great.
Per request, here is the code I'm using to cycle through the returning array:
foreach($client_comment as $item) {
print_r($item);
print '<br /><br />';
}
Here are 2 queries that print all of the data to the screen separately. I want to combine these two queries in to 1 query:
$client_comment = db_query("SELECT comment.subject AS comment_subject, comment.cid AS cid, comment.nid AS comment_nid, comment.created AS comment_created
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
WHERE (( (comment.status <> '0') AND (node_comment.status = '1') AND (comment.nid = '$nid') ))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0");
// Get the comments associated TO the client from Caregiver node.
$client_associated_comment = db_query("SELECT comment.subject AS comment_subject, comment.cid AS cid, comment.nid AS comment_nid, comment.created AS comment_created
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
INNER JOIN {field_data_field_associated_client} associated_client ON comment.cid = associated_client.entity_id
WHERE (( (comment.status <> '0') AND (node_comment.status = '1') AND (associated_client.field_associated_client_nid = '$nid') ))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0");
foreach($client_comment as $item) {
$client_comment_array[] = $item;
}
foreach ($client_associated_comment as $item) {
$client_comment_array[] = $item;
}
foreach($client_comment_array as $item) {
print_r($item);
print '<br /><br />';
}
Alright, I solved it by using LEFT JOIN instead of INNER JOIN. Resulting query:
$client_comment = db_query("SELECT comment.subject AS comment_subject,
comment.cid AS cid,
comment.nid AS comment_nid,
comment.created AS comment_created
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
LEFT JOIN {field_data_field_associated_client} associated_client ON comment.cid = associated_client.entity_id
WHERE (( (associated_client.field_associated_client_nid = '$nid')
OR (comment.nid = '$nid') )
AND (comment.status <> '0')
AND (node_comment.status = '1') )
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0");
foreach($client_comment as $item) {
print_r($item);
print '<br /><br />';
}

How do I display *all* the filters in layered navigation?

I am using "Layered Navigation SEO" from magento connect.
It's working flawlessly.
But I want the filters(with results) to be displayed always. My requirement is not similar to other questions found here.
for example...
In the computers category (working with sample data) there are 4 brands and three colors (black, brown and silver)
I select "Apple" as brand the available colors would be silver alone, but I want to display all the 3 colors as before (remember... NOT all the colors like pink, magenta, etc.)
If I select filter(no results) all colors like white, magento, pink, etc. will be displayed, which I don't want
I want only the filters which are related to category initially.
I am new to magento coding
Any help?
If more clarity is needed I'll be able to provide...
in app\code\local\Catalin\SEO\Model\Catalog\Resource\Layer\Filter\Attribute.php
edit public function getCount($filter)
goto last line
change return $connection->fetchPairs($select); to...
$pairCarry = $connection->fetchPairs($select);
$pairCarryfin = $this->checkTheAttributes($pairCarry, $tableAlias, $attribute);
return $pairCarryfin;
then add the function below it...
public function checkTheAttributes($pairCarry, $tableAlias, $attribute){
$category = Mage::registry('current_category');
if($category){
$query = "SELECT DISTINCT `$tableAlias`.`value`, COUNT($tableAlias.entity_id) AS `count` FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id=".$category->getStoreId()." AND cat_index.visibility IN(2, 4) AND cat_index.category_id='".$category->getId()."'
INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0
INNER JOIN `catalog_product_index_eav` AS `$tableAlias` ON $tableAlias.entity_id = e.entity_id AND $tableAlias.attribute_id = '".$attribute->getAttributeId()."' AND $tableAlias.store_id = '".$category->getStoreId()."' GROUP BY `$tableAlias`.`value`";
}
else{
$query = "SELECT DISTINCT `$tableAlias`.`value`, COUNT($tableAlias.entity_id) AS `count` FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id=1 AND cat_index.visibility IN(2, 4)
INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0
INNER JOIN `catalog_product_index_eav` AS `$tableAlias` ON $tableAlias.entity_id = e.entity_id AND $tableAlias.attribute_id = '".$attribute->getAttributeId()."' AND $tableAlias.store_id = 1 GROUP BY `$tableAlias`.`value`";
}
$connection = $this->_getReadAdapter();
$pairCarry_inter = $connection->fetchPairs($query);
if(!empty($pairCarry)){
$odd = array_diff_key($pairCarry_inter, $pairCarry);
if(!empty($odd)){
foreach($odd as $k=>$v){
$odd[$k] = 0;
}
$pairCarry_inter = $pairCarry + $odd;
}
}
else{
foreach($pairCarry_inter as $k => $v){
$pairCarry_inter[$k] = 0;
}
}
$pairCarry_complete = $pairCarry_inter;
return $pairCarry_complete;
}

How Can I use Alias in Where

This is my code but it's not working:
$select = $db->select()
->from(array('p' => 'products'), 'p.product_id')
->columns(array('x' => new Zend_Db_Expr('(SELECT...)'
)))
->where('x = ?', 'value');
// Alternatively use columns('p.product_name')
How can I retrieve x and compere it in where clause?
This is the actual query:
SELECT `abstract_submission`.*,
(SELECT GROUP_CONCAT(CONCAT(user.firstName, " ", user.lastName) SEPARATOR ",")
FROM mamba_event.abstract_submission_reviewer reviewer INNER JOIN
mamba_account.account_user user ON user.id = reviewer.userId
WHERE reviewer.submissionId = mamba_event.abstract_submission.id AND
user.isEnabled = 1)
AS `reviewers`,
(SELECT GROUP_CONCAT(CONCAT(author.firstName, " ", author.lastName) SEPARATOR ",")
FROM mamba_event.abstract_author author INNER JOIN
mamba_event.abstract_submission_author map ON author.id = map.authorId
WHERE map.submissionId = mamba_event.abstract_submission.id)
AS `allAuthors`,
(SELECT COUNT(`abstract_paper`.`id`) FROM `mamba_event`.`abstract_paper`
WHERE `abstract_paper`.`submissionId` = `abstract_submission`.`id`)
AS `numPapers`,
(SELECT `paperNumber` FROM `mamba_event`.`abstract_paper`
WHERE `abstract_paper`.`submissionId` = `abstract_submission`.`id` AND
`abstract_paper`.`currentStatus` = 3 LIMIT 1)
AS `acceptedPaperNumber`,
(SELECT IF ((COUNT(1) > 0), 'Paper has been uploaded','None') AS hasUploadedPaper
FROM `mamba_event`.`abstract_paper` paper
WHERE paper.submissionId = `mamba_event`.`abstract_submission`.`id`)
AS `hasUploadedPaper`,
(SELECT GROUP_CONCAT(CONCAT(user.firstName, " ", user.lastName) SEPARATOR ",")
FROM `mamba_event`.`abstract_submission_reviewer` reviewer INNER JOIN
`mamba_account`.`account_user` user ON user.id = reviewer.userId
WHERE reviewer.submissionId = `mamba_event`.`abstract_submission`.`id`
AND reviewer.hasConflictOfInterest = 1
AND user.isEnabled = 1)
AS `reviewersWithConflict`,
(SELECT AVG(`score`) FROM `mamba_event`.`abstract_submission_score`
WHERE `submissionId` = `abstract_submission`.`id`)
AS `averageScore`,
(SELECT AVG(`score`) FROM `mamba_event`.`abstract_paper_score`, `mamba_event`.`abstract_paper`
WHERE `abstract_paper_score`.`paperId` = `abstract_paper`.`id`
AND `abstract_paper`.`submissionId` = `abstract_submission`.`id`
AND (`abstract_paper`.`currentStatus` = 1
OR `abstract_paper`.`currentStatus` = 3))
AS `averagePaperScore`,
(SELECT AVG(`score`*`scoreWeight`) FROM `mamba_event`.`abstract_submission_score` INNER JOIN
`mamba_event`.`abstract_request_criteria` ON `criteriaId` = `abstract_request_criteria`.`id`
WHERE `submissionId` = `abstract_submission`.`id`)
AS `averageWeightedScore`,
(SELECT AVG(`score`*`scoreWeight`) FROM `mamba_event`.`abstract_paper_score` JOIN
`mamba_event`.`abstract_paper` INNER JOIN
`mamba_event`.`abstract_request_criteria` ON
`criteriaId` = `abstract_request_criteria`.`id`
WHERE `abstract_paper_score`.`paperId` = `abstract_paper`.`id`
AND `abstract_paper`.`submissionId` = `abstract_submission`.`id`
AND (`abstract_paper`.`currentStatus` = 1
OR `abstract_paper`.`currentStatus` = 3))
AS `averageWeightedPaperScore`, `author`.`email`
AS `authorEmail`, `author`.`salutation`
AS `authorTitle`, `author`.`firstName`
AS `authorFirstName`, `author`.`lastName`
AS `authorLastName`, `author`.`organisation`
AS `authorOrganisation`, `author`.`position`
AS `authorPosition`, `author`.`department`
AS `authorDepartment`, `author`.`phone`
AS `authorPhone`, `author`.`fax`
AS `authorFax`, `address`.`line1`
AS `addressLine1`, `address`.`line2`
AS `addressLine2`, `address`.`line3`
AS `addressLine3`, `address`.`line4`
AS `addressLine4`, `address`.`city`
AS `addressCity`, `address`.`stateCode`
AS `addressStateCode`, `address`.`countryCode`
AS `addressCountryCode`, `address`.`postalCode`
AS `addressPostalCode`, `author`.`biography`
AS `authorBiography`, `request`.`title`
AS `request`, `request`.`blindReview`, `request`.`hasCustomTypes`, `file`.`content_type`, `file`.`original_filename` AS `filename`, `author`.`speakerId`,
(SELECT GROUP_CONCAT(
CONCAT('',ifnull(author.firstName,'-'),' ',
ifnull(author.lastName,'-'),'
(',ifnull(author.organisation,'-'),',
',ifnull(author.authorCountryCode,'-'),')')
SEPARATOR ",")
FROM `mamba_event`.`abstract_author` author LEFT JOIN
`mamba_event`.`abstract_submission_author` sa
ON sa.authorId = author.id
WHERE sa.submissionId = `abstract_submission`.`id`)
AS `authorDetails`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2185'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2185`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2335'
AND `field`.`fieldValue` = 'BSCS'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2335`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2336'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2336` FROM `mamba_event`.`abstract_submission`
INNER JOIN `mamba_event`.`abstract_request` AS `request` ON requestId = request.id
LEFT JOIN `mamba_account`.`account_file` AS `file` ON fileId = file.id
INNER JOIN `mamba_event`.`abstract_author` AS `author` ON `presenterId` = `author`.`id`
LEFT JOIN `mamba_general`.`address` ON `author`.`addressId` = `address`.`id` WHERE ((`abstract_submission`.`isEnabled` = '1') AND (`abstract_submission`.`eventId` = '1893')) AND (`field2335` LIKE "%BSCS%") ORDER BY `request` asc LIMIT 15
You could do it with HAVING, like Muhammad Zeeshan said.
$select = $db->select()
->from(array('p' => 'products'), 'p.product_id')
->columns(array('x' => new Zend_Db_Expr('(SELECT...)')))
->having('x = ?', 'value');

Categories