How to find the Total Records of outer query - php

This is my query
SELECT concat(sf.from_location, "-",sf.to_location) as from_to_city,
count( *) as seach_count,
(SELECT count(DISTINCT fb.origin) as no_of_book
FROM flight_booking_details as fb
WHERE fb.status="BOOKING_CONFIRMED" and
from_code=journey_from and
to_code=journey_to AND
DATE(fb.created_datetime) >="2018-07-01" AND
DATE(fb.created_datetime) <="2018-07-04" AND
fb.journey_from = 'BLR' AND
fb.journey_to = 'DEL' ) as booking_count
FROM search_flight_history sf
WHERE DATE(sf.created_datetime) >= '2018-07-01' AND
DATE(sf.created_datetime) <= '2018-07-04' AND
(sf.from_location = 'BLR' OR
sf.from_code = 'BLR') AND
(sf.to_location = 'DEL' OR
sf.to_code = 'DEL')
GROUP BY from_code,
to_code
Here I need to find the Total Records of this query.
Please any one help me to find this one

If really just need the count of rows returned by your query, you can try the following:
select count(*)
from
(
SELECT concat(sf.from_location, "-",sf.to_location) as from_to_city,
count( *) as seach_count,
(SELECT count(DISTINCT fb.origin) as no_of_book
FROM flight_booking_details as fb
WHERE fb.status="BOOKING_CONFIRMED" and
from_code=journey_from and
to_code=journey_to AND
DATE(fb.created_datetime) >="2018-07-01" AND
DATE(fb.created_datetime) <="2018-07-04" AND
fb.journey_from = 'BLR' AND
fb.journey_to = 'DEL' ) as booking_count
FROM search_flight_history sf
WHERE DATE(sf.created_datetime) >= '2018-07-01' AND
DATE(sf.created_datetime) <= '2018-07-04' AND
(sf.from_location = 'BLR' OR
sf.from_code = 'BLR') AND
(sf.to_location = 'DEL' OR
sf.to_code = 'DEL')
GROUP BY from_code,
to_code
) X;

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

how to combine two queries to produce one result in codigniter

this is my query working fine
$offset = ($this->uri->segment(4))?$this->uri->segment(4):0;
$limit =10;
i donn't use $user_id becoz this function uses pagination
$q = "select distinct attandence.user_id ,monthname(date), sum(is_absent) as absents,in_time,out_time , count(date) as working_days, leave_type , users.f_name ,leave_types.type ,leave_types.leave_type_id , users.l_name ,( select count(leave_type) from attandence where leave_type != 0 and user_id = 4 and month(date) = 10 ) as leave_count from attandence join users on (users.user_id = attandence.user_id) left join leave_types on(leave_types.leave_type_id = attandence.leave_type) where in_time != '' and out_time != '' ".$where_condition." GROUP BY attandence.user_id LIMIT ".$limit." OFFSET ". $offset;
$rows = $this->attandence_model->q($q);
$this->data['Details'] = $rows;
in view i just passed
<? foreach ($Details as $detail){ ?>
<? } ?>
Any help is going to be appreciated. :)
I have solution your query you can add sub query Sub query
See Example:
$q = "select distinct attandence.user_id ,monthname(date), sum(is_absent) as absents,in_time,out_time , count(date) as working_days, leave_type , users.f_name ,leave_types.type ,leave_types.leave_type_id , users.l_name, (select count(leave_type) from attandence where leave_type != 0 and user_id = 15 and month(date) = 10) as leave_count from attandence join users on (users.user_id = attandence.user_id) left join leave_types on(leave_types.leave_type_id = attandence.leave_type) where in_time != '' and out_time != '' ".$where_condition." GROUP BY attandence.user_id LIMIT ".$limit." OFFSET ". $offset;

Adding condition to mysql query and fetch again

I have 3 queries which I run which are nearly identical, the latter two have an AND condition.
Main query:
$mess = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ?
ORDER BY cm.date DESC LIMIT 30 ) ddd
ORDER BY date ASC ");
$mess->bind_param("i", $room);
$mess->execute();
$mess->store_result();
$mess->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row = $mess->fetch()){
//im fetching here in my <div class='div1' >
}
Then, in the second div I have to add an AND condition:
$mess2 = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ? AND voteup - votedown >= 5
ORDER BY cm.date DESC LIMIT 30 ) ddd
ORDER BY date ASC ");
$mess2->bind_param("i", $room);
$mess2->execute();
$mess2->store_result();
$mess2->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row2 = $mess2->fetch()){
//im fetching here in my <div class='div2' >
}
Lastly, in the third div I have a slightly different AND condition:
$mess3 = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ? AND votedown - voteup >= 5
ORDER BY cm.date DESC LIMIT 30 ) ddd
ORDER BY date ASC ");
$mess3->bind_param("i", $room);
$mess3->execute();
$mess3->store_result();
$mess3->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row3 = $mess3->fetch()){
//im fetching here in my <div class='div3' >
}
Everything works BUT doing this near-same query seems clumsy. Is it possible to construct the same thing with only one query? I have used $mess->data_seek(0); but its not helping because I didn't add my condition to the query.
Just go for PhP to filter your data instead of triple query your database. In this case you can figure out to go for this solution because you call 3 times your query with the same parameter :
$mess3 = $mysqli->prepare(" SELECT *
FROM ( SELECT cm.id ,
cm.userid,
cm.message,
cm.voteup,
cm.votedown,
cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ?
AND votedown - voteup >= 5
ORDER BY cm.date DESC LIMIT 30 ) ddd
ORDER BY date ASC ");
$mess3->bind_param("i", $room);
$mess3->execute();
$mess3->store_result();
$mess3->bind_result($chatid,$chat_userid ,$message,$voteup,$votedown ,$date);
while($row = $mess3->fetch()){
$voteup = $row['voteup'];
$votedown = $row['votedown'];
addToDiv1($row);
if( $voteup - $votedown >= 5 ) {
addToDiv2($row);
}
if( $votedown - $voteup >= 5 ) {
addToDiv3($row);
}
}
I will just give an answer based specifically on cleaning up your code. Technically you will still make the 3 calls in this scenario, but it will be cleaner because you include one function only, you don't see the script behind it.
As I mentioned, I am not an SQL aficionado so I can not give a good solution there (maybe you can use GROUP BY and perhaps an OR clause...I don't really know...). If I were to do this, I would do a function that can return all the options:
/core/functions/getChatMessages.php
function getChatMessages($settings,$mysqli)
{
$id = (!empty($settings['id']))? $settings['id'] : false;
$type = (!empty($settings['type']))? $settings['type'] : false;
$max = (!empty($settings['max']))? $settings['max'] : 30;
$mod = '';
// No id, just stop
if(!is_numeric($id))
return false;
// equation one
if($type == 'up')
$mod = ' AND voteup - votedown >= 5';
// equation two
elseif($type == 'down')
$mod = ' AND votedown - voteup >= 5';
$mess = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ? {$mod}
ORDER BY cm.date DESC LIMIT {$max} ) ddd
ORDER BY date ASC");
$mess->bind_param("i", $id);
$mess->execute();
$mess->store_result();
$mess->bind_result($chatid, $chat_userid, $message, $voteup, $votedown, $date);
while($mess->fetch()){
$result[] = array(
'chatid'=>$chatid,
'chat_userid'=>$chat_userid,
'message'=>$message,
'voteup'=>$voteup,
'votedown'=>$votedown
);
}
// Send back the data
return (!empty($result))? $result : array();
}
To use:
// Include our handy function
require_once('/core/functions/getChatMessages.php');
// Store our id for use
$settings['id'] = 100;
// Should get 30 from first select
$voteGen = getChatMessages($settings,$mysqli);
// Should get 30 from second select
$settings['type'] = 'up';
$voteUp = getChatMessages($settings,$mysqli);
// Should get 15 from third select
// Just for the heck of it, I added in a limit settings
$settings['max'] = 15;
$settings['type'] = 'down';
$voteDown = getChatMessages($settings,$mysqli);
Now that you have these stored, just use a foreach loop to place them into your view. The good side of this is that you can call this where ever and when ever since the function only returns data. It allows you to work with the data in a view or non-view situation. Side note, I use PDO, so if there is something ineffective with the way the mysqli is fetching, that will be why. It's probably just best to fetch an assoc array to return...

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.

condition in a mysql statement

I'm trying to write a condition in my mysql query:
SELECT g.* FROM groups AS g
JOIN users AS u
ON u.user_posts >= g.post_min
AND u.user_posts <= g.post_max
AND u.points >= g.point_min
AND u.points <= g.point_max
AND u.uid = "'.$uid.'"
how should i write a condition when the g.post_max or g.point_max equal to 0 the statement dosen't need to include max values
$sql = 'SELECT g.id,g.point_amount
FROM groups AS g
JOIN users AS u
ON u.user_posts >= g.post_min
AND (u.user_posts <= g.post_max OR (g.post_max=0 OR g.point_max=0))
AND u.points >= g.point_min
AND (u.points <= g.point_max OR (g.post_max=0 OR g.point_max=0))
AND u.uid = "'.$uid.'"
LIMIT 1';
Join them with an OR; either the skip condition is true, OR the term can't be skipped:
(g.post_max = 0) OR (u.user_posts <= g.post_max)
(g.point_max = 0) OR (u.points <= g.point_max)
EDIT: inserting it into your query:
$sql = 'SELECT g.id,g.point_amount
FROM groups AS g
JOIN users AS u
ON u.user_posts >= g.post_min
AND u.points >= g.point_min
AND ((g.post_max = 0) OR (u.user_posts <= g.post_max))
AND ((g.point_max = 0) OR (u.points <= g.point_max))
AND u.uid = "'.$uid.'"
LIMIT 1';
EDIT again: I fail at reading; misunderstood your question. This is what it should look like.

Categories