I have the following in one of my functions but would like to refer to it as an alias named Date:
$loads = $query->get()->groupBy(function($item){
return Carbon::parse($item->dateTime)->format('F j, Y');
});
This $query starts off as: $query = DB::table('loads')...
and the field dateTime is a timestamp.
Is there a proper way to do this to include the alias? Thanks!
//Update with entire Controller Function:
public function apiList(Request $request){
$query = DB::table('loads')
->leftJoin('shipments', 'loads.shipmentID', '=', 'shipments.id')
->leftJoin('equipment as tractor', 'loads.tractorID', '=', 'tractor.id')
->leftJoin('employees', 'loads.driverID', '=', 'employees.id')
->leftJoin('customers as shipperCustomer', 'shipments.ship_from', '=', 'shipperCustomer.id')
->leftJoin('customers as consigneeCustomer', 'shipments.ship_to', '=', 'consigneeCustomer.id')
->select('loads.id','shipments.pro_number','shipments.id','employees.last_name as driver','tractor.unit_id as tractor','loads.dateTime','shipperCustomer.customer_name as ShipperCustomerName','consigneeCustomer.customer_name as ConsigneeCustomerName','shipments.cn_shipfromName as ShipperName','shipments.cn_shiptoName as ConsigneeName');
if($request->type){
$query->where('loads.type', $request->type);
}
if($request->status){
$query->where('loads.status', $request->status);
}
if($request->type == 1 && $request->status == 2){
$query->whereIn('shipmentID', function ( $query ) {
$query->select('shipmentID')->from('loads')->groupBy('shipmentID')->havingRaw('count(*) = 1');
});
}
$loads = $query->get()->groupBy(function($item)
{
return Carbon::parse($item->dateTime)->format('F j, Y');
});
return response()->json([
['loads'=>$loads],
['time'=>Carbon::now()]
]);
//UPDATE TO SHOW CURRENT RETURNED DATA:
///
Unfortunately, I get the following:
"SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'truckin.loads.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select loads.id, shipments.pro_number, shipments.id, employees.last_name as driver, tractor.unit_id as tractor, loads.dateTime as loadsDT, shipperCustomer.customer_name as ShipperCustomerName, consigneeCustomer.customer_name as ConsigneeCustomerName, shipments.cn_shipfromName as ShipperName, shipments.cn_shiptoName as ConsigneeName from loads left join shipments on loads.shipmentID = shipments.id left join equipment as tractor on loads.tractorID = tractor.id left join employees on loads.driverID = employees.id left join customers as shipperCustomer on shipments.ship_from = shipperCustomer.id left join customers as consigneeCustomer on shipments.ship_to = consigneeCustomer.id where loads.type = 1 and loads.status = 2 and shipmentID in (select shipmentID from loads group by shipmentID having count(*) = 1) group by DATE_FORMAT(loads.dateTime, "%M %e, %Y"))"
//Update with Another Return
//A couple of Updates -- August 30, 2018
Based on your original suggestion, I made the updates but received this error:
"SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'truckin.shipments.pro_number' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select ANY_VALUE(loads.id), shipments.pro_number, shipments.id, employees.last_name as driver, tractor.unit_id as tractor, loads.dateTime, shipperCustomer.customer_name as ShipperCustomerName,consigneeCustomer.customer_name as ConsigneeCustomerName,shipments.cn_shipfromName as ShipperName,shipments.cn_shiptoName as ConsigneeName from loads left join shipments on loads.shipmentID = shipments.id left join equipment as tractor on loads.tractorID = tractor.id left join employees on loads.driverID = employees.id left join customers as shipperCustomer on shipments.ship_from = shipperCustomer.id left join customers as consigneeCustomer on shipments.ship_to = consigneeCustomer.id where loads.type = 2 and loads.status = 1 group by DATE_FORMAT(loads.dateTime, "%M %e, %Y"))"
So I went ahead, and ended up having to do the following due to a cascading failure:
$loads = $query->groupBy(DB::raw('DATE_FORMAT(loads.dateTime, "%M %e, %Y")'), 'loads.dateTime','shipments.id', 'shipments.pro_number','driver','tractor','ShipperCustomerName','ConsigneeCustomerName','ShipperName','ConsigneeName')->get();
Now obviously this isn't right, but it was the only way I could get a return of any sort, which ended up being the following:
One last approach, change this:
select('loads.id','shipments.pro_number','shipments.id','employees.last_name as driver','tractor.unit_id as tractor','loads.dateTime','shipperCustomer.customer_name as ShipperCustomerName','consigneeCustomer.customer_name as ConsigneeCustomerName','shipments.cn_shipfromName as ShipperName','shipments.cn_shiptoName as ConsigneeName');
To this:
selectRaw('ANY_VALUE(loads.id), shipments.pro_number, shipments.id, employees.last_name as driver, tractor.unit_id as tractor, loads.dateTime, shipperCustomer.customer_name as ShipperCustomerName,consigneeCustomer.customer_name as ConsigneeCustomerName,shipments.cn_shipfromName as ShipperName,shipments.cn_shiptoName as ConsigneeName');
And leave the groupBy as
$query->groupBy(DB::raw('DATE_FORMAT(loads.dateTime, "%M %e, %Y")'))->get();
If you want to know more about this solution check: https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_any-value
Check the example on the link and take care of what im quoting down here:
The failure occurs because address is a nonaggregated column that is neither named among GROUP BY columns nor functionally dependent on them. As a result, the address value for rows within each name group is nondeterministic. There are multiple ways to cause MySQL to accept the query:
Alter the table to make name a primary key or a unique NOT NULL column. This enables MySQL to determine that address is functionally dependent on name; that is, address is uniquely determined by name. (This technique is inapplicable if NULL must be permitted as a valid name value.)
Use ANY_VALUE() to refer to address:
SELECT name, ANY_VALUE(address), MAX(age) FROM t GROUP BY name;
In this case, MySQL ignores the nondeterminism of address values within each name group and accepts the query. This may be useful if you simply do not care which value of a nonaggregated column is chosen for each group. ANY_VALUE() is not an aggregate function, unlike functions such as SUM() or COUNT(). It simply acts to suppress the test for nondeterminism.
Disable ONLY_FULL_GROUP_BY. This is equivalent to using ANY_VALUE() with ONLY_FULL_GROUP_BY enabled, as described in the previous item.
In the configuration of database at config/database.php change strict =>false
Default it is true
Related
$bo_facilities = DB::select('SELECT
a.bo_facility_code,
a.bo_facility_groupcode,
a.bo_number,
a.bo_indYesOrNo,
a.bo_indLogic,
b.bo_content_facility_description
FROM bo_facilities AS a
RIGHT JOIN bo_content_facilities AS b
ON b.bo_content_facility_code = a.bo_facility_code AND b.bo_content_facility_facilityGroupCode = a.bo_facility_groupcode
WHERE a.bo_hotel_code = "'.$hotel['code'].'" GROUP BY b.bo_content_facility_description');
Error message:
"message": "SQLSTATE[42000]: Syntax error or access violation: 1055
'philex.main.a.bo_facility_code' isn't in GROUP BY (SQL:
SELECT a.bo_facility_code,
a.bo_facility_groupcode,
a.bo_number,
a.bo_indyesorno,
a.bo_indlogic,
b.bo_content_facility_description
FROM bo_facilities AS a
right join bo_content_facilities AS b
ON b.bo_content_facility_code = a.bo_facility_code
AND b.bo_content_facility_facilitygroupcode =
a.bo_facility_groupcode
WHERE a.bo_hotel_code = "'.$hotel['code'].'"
GROUP BY b.bo_content_facility_description
)",
I was getting this error because of the GROUP BY method.
Take a look at the aggregate functions in mysql.
If you group your results by b.bo_content_facility_description the others fields in the SELECT that are not in the GROUP BY should be aggregated with a function like SUM, COUNT, etc.
Grouping by that single field without any arregation on the other fields is meaningful, because you are not specifying how to combine the other fields to get the single record for the grouped field.
I suggest you to clear your head about what results you expect.
I need to get specific columns from three tables through joins.every time it goes wrong.my code is
$saf=mysqli_query($db , "select pod.mobile, tpaidamount.Aptdate, follow.cent, pdate, time from pod,tpaidamount, follow where tpaidamount.pid = follow.pid and pod.Customer Id = tpaidamount.pid and pod.Customer Id =follow.pid ");
$i=1;
while($sfg=mysqli_fetch_assoc($saf) or die(mysqli_error($db)))
;
?>
pod,tpaidamount,follow are tables and other coloumns
Getting error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Id = tpaidamount.pid and pod.Customer Id =follow.pid' at line 1
is it a typo? Is setfollowup.pid or follow.pid?
select pod.mobile, tpaidamount.Aptdate, follow.cent, <table>.pdate, <table>.time
from pod, tpaidamount, follow
where tpaidamount.pid = follow.pid
and pod.`Customer Id` = tpaidamount.pid
and pod.`Customer Id` = follow.pid
You shouldn't Ever create columns names with spaces. The name: "pod.Customer Id" is a Bad attribute name, and you need to avoid use names like datatypes (or any SGBD reserved word) like: 'date', 'time', 'char', 'table', 'column'....
However, if you need to do it, try this SQL:
SELECT p.mobile
, t.Aptdate
, f.cent
, ???.pdate
, ???.`time`
FROM pod AS p
JOIN tpaidamount AS t ON o.`Customer Id` = t.pid
JOIN follow AS f ON t.pid = f.pid ON p.`Customer Id` = f.pid
Use alias for easy coding SQL queryes. Ex: table_name AS tn, table_a_name AS tan.
!!! I sugest you to watch some basic SQL Lessons.
Good Luck.
After trying to query the following nested query
SELECT ur.userID, us.fullname
FROM tbl_user_recipe AS ur JOIN tbl_user_settings AS us ON ur.userID = us.userID
WHERE relationship = 'analyzed' AND userID IN
( SELECT ux.userID
FROM tbl_user_recipe AS ux
WHERE ux.relationship = 'collected'
);
I'm getting the following, and idea why?
#1052 - Column 'userID' in IN/ALL/ANY subquery is ambiguous
You need to prefix the alias to the table here:
WHERE relationship = 'analyzed' AND ur.userID IN
I have the following SQL query, which has a subquery in it:
SELECT * FROM `statics` WHERE `mmsi`=
(SELECT `mmsi` FROM `positions`,`active`
WHERE `active.mmsi` = `positions.position_ID`);
But when I execute it, I get the following error:
1052 - Column 'mmsi' in field list is ambiguous
Please help me on adjusting my query.
Without seeing your table structure, this is a wild guess:
SELECT *
FROM `statics`
WHERE `statics.mmsi` = (SELECT `active.mmsi`
FROM `positions`,`active`
WHERE `active.mmsi` = `positions.position_ID`);
but I don't get why are you doing this with a subquery. This one should yield the same results
SELECT statics.*
FROM `statics`, `positions`
WHERE `statics.mmsi` = `positions.position_ID`;
I have two tables 'accounts_transactions' and 'accounts_bills_transactions'.
I have to left join these two using active record of codeigniter.But the names of key columns used to join are different.So I am not getting the key column from the left table in the output .What query should I write to get the key column from the left table included in the result.
My code is
$this->db->select('*');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_bills_transactions.transaction_id','left');
$query = $this->db->get();
So, as you see the key columns used to join here are , id from left table and transaction_id from second table.The problem is that I am not getting the id from left table in the result.But I am getting all other columns.I assume the problem is because of difference in column names used to join.ie both the column names are not named 'id' .So how can I get the id from left table included in the result.
You could alias them:
$this->db->select('accounts_transatctions.*, account_transactions.id AS a_id,
accounts_bills_transactions.*,
account_bills_transactions.id AS ab_id');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_transactions.transaction_id','left');
$query = $this->db->get();
The two IDs will now be available as a_id and ab_id (or whatever alias you choose)
Note: I'm not sure if you can alias in AR without avoiding escaping (haven't been using CI for a while). Should you get any error for that reason, just pass false as second parameter of $this->db->select():
$this->db->select('...', false);
you can try this if you confuse of using $this->where or $this->join
$query = $this->db->query("select ......");
return $query;
You problem is so simple. You can use this query
$query = $this->db
->select('at.*')
->select('abt.id as abt_id');
->from('accounts_transactions at');
->join('accounts_bills_transactions abt', 'at.id = abt.transaction_id','left');
->get()
->result();
When same column are used in join it selects only one. You need to give alise to the other column in second table. The best practice is to use a structure like this
accounts_transatctions
--------------------------
accounts_transatctions_id
other_columns
accounts_bills_transactions
---------------------------
accounts_bills_transactions_id
accounts_transatctions_id
other_columns