I keep getting this error, and found only answers to users of laravel..
I have this query:
$stmt = $pdo->query("SELECT branches.branch_id, branches.branch_name,
tasks.task_name, tasks.task_status, tasks.real_amount,
tasks.task_start, tasks.task_finish, tasks.description, projects.proj_name, projects.project_id
FROM retail2.branches, retail2.projects, retail2.tasks
JOIN tasks ON tasks.branch_id = branches.branch_id;
JOIN branches_projects ON projects.project_id = branches_projects.proj_id
JOIN branches ON branches.branch_id = branches_projects.branch_id");
and I've been trying to debug but I can't find out what the issue is... any suggestion please? Thanks!
You don't need to list tables in both the FROM and JOIN clauses. You just need to reorder the JOIN clauses, because a JOIN can only refer to tables in previous JOIN or FROM clauses.
You also have a ; in the middle of the query, at the end of the JOIN tasks line. Everything after that is not part of the query, and this will cause an error becauase PDO doesn't allow multiple queries in one call.
SELECT branches.branch_id, branches.branch_name,
tasks.task_name, tasks.task_status, tasks.real_amount,
tasks.task_start, tasks.task_finish, tasks.description, projects.proj_name, projects.project_id
FROM projects
JOIN branches_projects ON projects.project_id = branches_projects.proj_id
JOIN branches ON branches.branch_id = branches_projects.branch_id
JOIN tasks ON tasks.branch_id = branches.branch_id;
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
I want to get next and previous record in my database, this is my first time using DQL and I don't really understand why it doesn't work.
Here's how my custom query look like:
$em = $this->getDoctrine()->getManager();
$rsm = new ResultSetMapping();
$rsm->addScalarResult('id', 'id');
$query = $em->createNativeQuery(
'SELECT id
FROM SITEArticlesBundle:Article
WHERE
id = (SELECT id
FROM SITEArticlesBundle:Article
WHERE ? > 2 LIMIT 1)
OR
id = (SELECT id
FROM SITEArticlesBundle:Article
WHERE ? < 2 LIMIT 1)', $rsm);
$query->setParameter(1, $id);
$query->setParameter(2, $id);
$nextAndPrevNews = $query->execute();
I want to get array of 2 id, like that:
[
['id' => 1]
['id' => 3]
]
But I get a SQL syntax error
SQLSTATE[42000]: Syntax error or access violation: 1064 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 ':Article
WHERE
id = (SELECT id
FROM ' at line 2
I would be really grateful if someone could help me.
Thanks
One issue is the colon character in the table name. That character isn't allowed, unless the table name is escaped.
I suspect that SITEArticlesBundle:Article isn't the actual identifier for the MySQL table. In a native query, you need to specify the actual name of the MySQL table.
If that is your tablename, then you can enclose it in backtick characters:
FROM `SITEArticlesBundle:Article`
I'm not sure why you'd be comparing the value of $id with a literal 2, and not comparing that to the value of the id column in the table. I don't get it.
Unless you are trying to pass in the column name as a bind parameter, which won't work. You can only pass in values to a prepared SQL statement, you can't pass identifiers or keywords or other SQL constructs in as bind parameters.
Personally, I'd avoid the OR condition and the subqueries, and just use a UNION ALL operation.
SELECT MAX(p.id) AS id
FROM `SITEArticlesBundle:Article` p
WHERE p.id < ?
UNION ALL
SELECT MIN(n.id) AS id
FROM `SITEArticlesBundle:Article` n
WHERE n.id > ?
this is my query:
$sql = "SELECT sum(CommitmentItemInvoices.Amount) AS PendTotal, CommitmentItemInvoices.Amount AS Amount_Pending , CommitmentItems.*, CommitmentItemInvoices.*
FROM CommitmentItemInvoices
LEFT JOIN CommitmentItems on CommitmentItems.commitmentItemId = CommitmentItemInvoices.commitmentItemId
WHERE (CommitmentItemInvoices.Status='new' AND CommitmentItemInvoices.commitmentItemId = :commitId)";
try{
//prepare statement
$stmt = $con->prepare ($sql);
//bind values to :username
$stmt->bindValue("commitId", $commitId, PDO::PARAM_STR);
$stmt->execute();
}catch(PDOException $e){
echo "Error: ".$e->getMessage();
}
I am getting the following error:
Error: SQLSTATE[42000]: Syntax error or access violation: 8120 [Microsoft][ODBC SQL Server Driver][SQL Server]Column 'CommitmentItemInvoices.Amount' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. (SQLExecute[8120] at ext\pdo_odbc\odbc_stmt.c:254)
Any idea as to what I am doing wrong in the SQL query?
You need a GROUP BY statement to allow the aggregate to work:
SELECT sum(cii.Amount) AS PendTotal
FROM CommitmentItemInvoices cii
LEFT JOIN CommitmentItems ci on
ci.commitmentItemId = cii.commitmentItemId
WHERE (cii.Status='new'
AND cii.commitmentItemId = :commitId)
#xQbert makes an excellent suggestion. Pull out all the fields and you'll see that the query works. Then add them one by one into the select and group by portion of your query. You'll see how the aggregation works.
The * in your query doesnt work because the sql engine needs to know how to aggregate your sum. You can aggregate by many fields, but they each need to be specified in the select AND in the group by.
You will likely get different results as you add more fields to group by.
Read up on GROUP BY to determine which fields you want to group to get the correct aggregation.
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`;