How to convert given multiple join query to ZendFrame work query - php

SELECT
`blg`.`id` ,
`blg`.`heading` ,
`blg`.`description` ,
`cat`.`name` AS `categoryname` ,
`mem`.`firstname` AS `user` ,
( SELECT COUNT( * ) FROM blog_comments WHERE blog_comments.status = '1' AND blog_comments.blogid = blg.id) AS `commentcount`
FROM `blogs` AS `blg`
INNER JOIN `blog_category` AS `cat` ON blg.category = cat.id
INNER JOIN `members_member` AS `mem` ON blg.user = mem.id
LEFT JOIN `blog_comments` AS `cmt` ON blg.id = cmt.blogid
WHERE ( blg.status = '1' )
GROUP BY blg.id ORDER BY `blg`.`id` ASC

What about something like this:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$dbExpr = new Zend_Db_Expr("(SELECT COUNT( * ) FROM blog_comments WHERE blog_comments.status = '1' AND blog_comments.blogid = blg.id) AS `commentcount`");
$select->from(
array('blg' => 'blogs'),
array('id', 'heading', 'description', 'name as categoryname', $dbExpr)
)->joinInner(
array('cat' => 'blog_category'),
'blg.category = cat.id',
array()
)->joinInner(
array('mem' => 'members_member'),
'blg.user = mem.id',
array()
)->joinLeft(
array('cmt' => 'blog_comments'),
'blg.id = cmt.blogid',
array()
)->where('blg.status = ?', '1')
->group('blg.id')
->order('blg.id ASC');
echo $select->assemble();
exit;
Output:
SELECT `blg`.`id`, `blg`.`heading`, `blg`.`description`, `blg`.`name` AS `categoryname`,
(SELECT COUNT( * ) FROM blog_comments WHERE blog_comments.status = '1' AND blog_comments.blogid = blg.id) AS `commentcount`
FROM `blogs` AS `blg`
INNER JOIN `blog_category` AS `cat` ON blg.category = cat.id
INNER JOIN `members_member` AS `mem` ON blg.user = mem.id
LEFT JOIN `blog_comments` AS `cmt` ON blg.id = cmt.blogid
WHERE (blg.status = '1')
GROUP BY `blg`.`id`
ORDER BY `blg`.`id` ASC

Related

my sql sub_query return_more than one row

Here is my mysql_query i want to add this query into my main query but the problem is when im add it to query it show sub query returns more than one row
(
SELECT date(trn_orderheader_approvedby.dtApprovedDate) AS CREATE_DATE
FROM trn_orderheader_approvedby
WHERE trn_orderheader_approvedby.intApproveLevelNo IN('-10')
)
AS Order_COMPLETED_DATE
SELECT
TB1.*, (
SELECT
SUM(TRNS.dblQty *- 1)
FROM
ware_stocktransactions_bulk AS TRNS
WHERE
TRNS.intOrderNo = TB1.`NO`
AND TRNS.intOrderYear = TB1.`YEAR`
AND TRNS.intSalesOrderId = TB1.intSalesOrderId
AND TRNS.intItemId = TB1.ITEM_ID
AND TRNS.intLocationId = TB1.LOCATION_ID
AND TRNS.strType IN ('ISSUE', 'RETSTORES')
) AS QTY,
(
SELECT
SUM(
TRNS.dblQty * TRNS.dblGRNRate * mst_financeexchangerate.dblBuying *- 1
)
FROM
ware_stocktransactions_bulk AS TRNS
LEFT JOIN mst_financeexchangerate ON mst_financeexchangerate.dtmDate = TRNS.dtGRNDate
AND mst_financeexchangerate.intCompanyId = TRNS.intCompanyId
AND mst_financeexchangerate.intCurrencyId = TRNS.intCurrencyId
WHERE
TRNS.intOrderNo = TB1.`NO`
AND TRNS.intOrderYear = TB1.`YEAR`
AND TRNS.intSalesOrderId = TB1.intSalesOrderId
AND TRNS.intItemId = TB1.ITEM_ID
AND TRNS.intLocationId = TB1.LOCATION_ID
AND TRNS.strType IN ('ISSUE', 'RETSTORES')
) AS AMOUNT,
(
SELECT
SUM(
costing_sample_header.INK_COST
)
FROM
costing_sample_header
WHERE
TB1.intSampleNo = costing_sample_header.SAMPLE_NO
AND TB1.intSampleYear = costing_sample_header.SAMPLE_YEAR
AND TB1.intRevisionNo = costing_sample_header.REVISION
AND TB1.strCombo = costing_sample_header.COMBO
AND TB1.strPrintName = costing_sample_header.PRINT
) AS INK_COST,
(
SELECT
SUM(
costing_sample_header.SPECIAL_RM_COST
)
FROM
costing_sample_header
WHERE
TB1.intSampleNo = costing_sample_header.SAMPLE_NO
AND TB1.intSampleYear = costing_sample_header.SAMPLE_YEAR
AND TB1.intRevisionNo = costing_sample_header.REVISION
AND TB1.strCombo = costing_sample_header.COMBO
AND TB1.strPrintName = costing_sample_header.PRINT
) AS RM_COST
FROM
(
SELECT DISTINCT
tempory_rm_moved_orders_summery2.`NO`,
tempory_rm_moved_orders_summery2.`YEAR`,
trn_orderdetails.intSalesOrderId,
trn_orderdetails.strSalesOrderNo,
trn_orderdetails.strGraphicNo,
trn_orderdetails.intSampleNo,
trn_orderdetails.intSampleYear,
trn_orderdetails.intRevisionNo,
trn_orderdetails.strCombo,
trn_orderdetails.strPrintName,
mst_part.strName AS part,
mst_locations.intId AS LOCATION_ID,
mst_locations.strName AS LOCATION,
trn_orderdetails.intQty,
mst_maincategory.strName AS MAIN_CATEGORY,
mst_subcategory.strName AS SUB_CATEGORY,
mst_item.intId AS ITEM_ID,
mst_item.strCode AS ITEM_CODE,
mst_item.strName AS ITEM_NAME,
mst_units.strCode AS UOM,
trn_po_prn_details_sales_order.PRODUCTION_QTY,
/* trn_po_prn_details_sales_order.CONS_PC,
trn_po_prn_details_sales_order.PRODUCTION_QTY,
trn_po_prn_details_sales_order.REQUIRED, sum( ifnull(
ware_stocktransactions_bulk.dblQty *- 1, 0 ) ) AS qty,*/
/*sum( ifnull( ware_stocktransactions_bulk.dblQty * ware_stocktransactions_bulk.dblGRNRate * mst_financeexchangerate.dblBuying *- 1, 0 ) ) AS amount, */
trn_orderdetails.dblPrice,
mst_customer.strName AS CUSTOMER_NAME,
mst_brand.strName AS BRAND_NAME,
trn_orderheader.intStatus,
IF (
trn_orderheader.intStatus = 1,
'Approved',
IF (
trn_orderheader.intStatus = 0,
'Rejected',
IF (
trn_orderheader.intStatus =- 10,
'Completed',
IF (
trn_orderheader.intStatus =- 2,
'Cancel',
IF (
trn_orderheader.intStatus =- 1,
'Revised',
'Pending'
)
)
)
)
) AS STATUS,
trn_orderdetails.dtDeliveryDate,
mst_technique_groups.TECHNIQUE_GROUP_NAME
FROM
ware_stocktransactions_bulk
INNER JOIN tempory_rm_moved_orders_summery2 ON ware_stocktransactions_bulk.intOrderNo = tempory_rm_moved_orders_summery2.`NO`
AND ware_stocktransactions_bulk.intOrderYear = tempory_rm_moved_orders_summery2.`YEAR`
AND date(
ware_stocktransactions_bulk.dtDate
) >= '2017-06-01'
INNER JOIN trn_orderdetails ON ware_stocktransactions_bulk.intOrderNo = trn_orderdetails.intOrderNo
AND ware_stocktransactions_bulk.intOrderYear = trn_orderdetails.intOrderYear
AND ware_stocktransactions_bulk.intSalesOrderId = trn_orderdetails.intSalesOrderId
INNER JOIN mst_part ON trn_orderdetails.intPart = mst_part.intId
INNER JOIN trn_orderheader ON trn_orderdetails.intOrderNo = trn_orderheader.intOrderNo
AND trn_orderdetails.intOrderYear = trn_orderheader.intOrderYear
INNER JOIN mst_item ON ware_stocktransactions_bulk.intItemId = mst_item.intId
INNER JOIN mst_maincategory ON mst_item.intMainCategory = mst_maincategory.intId
INNER JOIN mst_subcategory ON mst_item.intSubCategory = mst_subcategory.intId
INNER JOIN mst_units ON mst_item.intUOM = mst_units.intId
INNER JOIN mst_locations ON ware_stocktransactions_bulk.intLocationId = mst_locations.intId
INNER JOIN mst_customer ON trn_orderheader.intCustomer = mst_customer.intId
INNER JOIN trn_sampleinfomations ON trn_orderdetails.intSampleNo = trn_sampleinfomations.intSampleNo
AND trn_orderdetails.intSampleYear = trn_sampleinfomations.intSampleYear
AND trn_orderdetails.intRevisionNo = trn_sampleinfomations.intRevisionNo
INNER JOIN mst_brand ON trn_sampleinfomations.intBrand = mst_brand.intId
INNER JOIN mst_technique_groups ON trn_orderdetails.TECHNIQUE_GROUP_ID = mst_technique_groups.TECHNIQUE_GROUP_ID
LEFT JOIN trn_po_prn_details_sales_order ON ware_stocktransactions_bulk.intOrderYear = trn_po_prn_details_sales_order.ORDER_NO
AND ware_stocktransactions_bulk.intOrderYear = trn_po_prn_details_sales_order.ORDER_YEAR
AND ware_stocktransactions_bulk.intSalesOrderId = trn_po_prn_details_sales_order.SALES_ORDER
AND ware_stocktransactions_bulk.intItemId = trn_po_prn_details_sales_order.ITEM
WHERE
ware_stocktransactions_bulk.strType IN ('ISSUE', 'RETSTORES')
AND ware_stocktransactions_bulk.intOrderNo > 0
AND trn_po_prn_details_sales_order.ITEM IS NULL
/* GROUP BY ware_stocktransactions_bulk.intLocationId, ware_stocktransactions_bulk.intOrderNo, ware_stocktransactions_bulk.intOrderYear, ware_stocktransactions_bulk.intSalesOrderId, ware_stocktransactions_bulk.intItemId */
) AS TB1here
i found a solution like this
(
SELECT
trn_orderheader_approvedby.dtApprovedDate
FROM
trn_orderheader_approvedby
WHERE
trn_orderheader_approvedby.intApproveLevelNo = "-10"
AND trn_orderdetails.intOrderNo = trn_orderheader_approvedby.intOrderNo
AND trn_orderdetails.intOrderYear = trn_orderheader_approvedby.intYear
ORDER BY
trn_orderheader_approvedby.dtApprovedDate DESC
LIMIT 1
) AS COMPLETED_DATE

mysqli_fetch_assoc() is giving unexpected null values

This is my SQL query:
SELECT * FROM users,content
LEFT OUTER JOIN articles ON (
content.content_id = articles.content_id
AND content.content_type = 'article' )
LEFT OUTER JOIN projects ON (
content.content_id = projects.content_id
AND content.content_type = 'project' )
LEFT OUTER JOIN videos ON (
content.content_id = articles.content_id
AND content.content_type = 'video' )
WHERE (content.content_id IN (128,414,399,616,259))
AND content.author_id = users.u_id
order by FIELD(content.content_id,128,414,399,616,259)
when I run this on phpmyadmin I'm getting the results correctly but when I fetch the results by doing mysqli_fetch_assoc(), I am getting null values for content_id. Someone please help me with this. Thanks in advance
Edit:
This is my php code
$query = "SELECT *
FROM users,content
LEFT OUTER JOIN articles
ON ( content.content_id = articles.content_id
AND content.content_type = 'article' )
LEFT OUTER JOIN projects
ON ( content.content_id = projects.content_id
AND content.content_type = 'project' )
LEFT OUTER JOIN videos
ON ( content.content_id = articles.content_id
AND content.content_type = 'video' )
WHERE (content.content_id IN (".implode(",",$new_array).")) AND content.author_id = users.u_id order by FIELD(content.content_id,".implode(",",$new_array).")";
$result = mysqli_query($con,$query);
if($result!=null && $result->num_rows>0){
while( $contentrow = $mysqli_fetch_assoc($result){
print_r($contentrow);
}
}
$new_array is the content ids for which I'm querying the database. The printed $contentrow has content_id field as null while I'm getting the correct id values in phpmyadmin.

change SQL query from 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');
}
}
?>

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');

Invalid Use of Group Function

Much of the query was put in variables, but for the purpose of this question I have included them in the query. Margin is the sum of all the alias queries above it ($margin).
I am getting the error:
SQLSTATE[HY000]: General error: 1111 Invalid use of group function in company-performance-control.php on line 117
Here is my query:
$margin = $invoicesOut.'-'.$costs.'+'.$creditsIn.'-'.$creditsOut ;
$result = $dbh->query("SELECT CONCAT(MONTH(invoices_out.date), '/', YEAR(invoices_out.date)) AS theDate,
SUM(COALESCE(
(SELECT SUM(invoices_out.net/rate)
FROM invoices_out, (SELECT jobRef, invoiceRef FROM invoices_out_reference GROUP BY invoiceRef) AS unique_references
WHERE unique_references.invoiceRef = invoices_out.id
AND unique_references.jobRef = jobs.id
),
0)) AS invoiced,
SUM((SELECT SUM((quantity*parts_trading.sellingNet)/currencies.rateVsPound)
FROM parts_trading, currencies
WHERE parts_trading.sellingCurrency = currencies.id
AND parts_trading.enquiryRef = enquiries.id
AND jobs.id NOT IN
(SELECT DISTINCT jobRef FROM invoices_out_reference)
)
+
COALESCE(
(SELECT SUM(enquiries_custom_fees.feeAmountNet/currencies.rateVsPound)
FROM enquiries_custom_fees, parts_trading, currencies
WHERE enquiries_custom_fees.enquiryRef = enquiries.id
AND enquiries_custom_fees.enquiryRef = parts_trading.enquiryRef
AND parts_trading.sellingCurrency = currencies.id
),
0
)) AS pending,
SUM(COALESCE(
(SELECT SUM(net)
FROM credit_notes_supplier, parts_trading_buying
WHERE credit_notes_supplier.partRef = parts_trading_buying.id
AND parts_trading_buying.enquiryRef = enquiries.id)
,0
)) AS creditsIn,
SUM(COALESCE(
(SELECT SUM(net)
FROM credit_notes_customer, parts_trading
WHERE credit_notes_customer.partRef = parts_trading.id
AND parts_trading.enquiryRef = enquiries.id)
,0
)) AS creditsOut,
SUM(((SELECT SUM(qty*(parts_trading_buying.buyingNet/currencies.rateVsPound))
FROM parts_trading_buying, currencies
WHERE parts_trading_buying.buyingCurrency = currencies.id
AND parts_trading_buying.enquiryRef = enquiries.id
)
+
COALESCE(
(SELECT SUM(parts_trading_buying_charges.feeAmountNet)
FROM parts_trading_buying_charges, parts_trading_buying
WHERE parts_trading_buying_charges.partRef = parts_trading_buying.id
AND parts_trading_buying.enquiryRef = enquiries.id
)
, 0))) AS costs,
SUM($margin) AS margin
FROM jobs, enquiries, invoices_out,
(SELECT jobRef, invoiceRef
FROM invoices_out_reference
GROUP BY invoiceRef
) AS unique_invoice_refs
WHERE enquiries.id = jobs.enquiryRef
AND unique_invoice_refs.invoiceRef = invoices_out.id
AND jobs.id = unique_invoice_refs.jobRef
AND jobs.stateRef != 1
AND jobs.stateRef != 5
GROUP BY YEAR(invoices_out.date), MONTH(invoices_out.date)") ;
I have narrowed it down to these:
SUM($creditsIn) AS creditsIn
SUM($creditsOut) AS creditsOut
Which are defined as:
$creditsIn = 'COALESCE(
(SELECT SUM(net)
FROM credit_notes_supplier, parts_trading_buying
WHERE credit_notes_supplier.partRef = parts_trading_buying.id
AND parts_trading_buying.enquiryRef = enquiries.id)
,0
)' ;
$creditsOut = 'COALESCE(
(SELECT SUM(net)
FROM credit_notes_customer, parts_trading
WHERE credit_notes_customer.partRef = parts_trading.id
AND parts_trading.enquiryRef = enquiries.id)
,0
)' ;
What a big query!
Troubleshoot this. Simply remove each subquery one at a time and determine which query is causing this.

Categories