Laravel 5.8, Tricky subquery with Count(*) in where clause - mysql

I need to write a little tricky subquery in where clause
So, I have a query like this
Select * FROM table1
JOIN table2 ...
LEFT JOIN table3 ...
WHERE (SELECT COUNT(*) FROM some_table where some_condition) = 0;
The SQL works fine, but how can I move it into the Laravel?
Yeah, I know that I should use DB::raw() but the problem is the subquery returns count. So, for example, the count is 5454. After that, I'm having something like this.
->where(5454, '=', 0)
and it gives me obvious error message: Unknown column 5454 ...
I've tried also to use AS count for the subquery but in that case, I'm having another obvious error message: Syntax error 0_0
So, any suggestions?

Try
whereRaw("(SELECT COUNT(*) FROM some_table where some_condition) = 0")
This will help you.

Related

Unknown column 'r' in field list

I've been working on a SQL query for a project, and I face an error message when I want to use it.
Here is the query itself :
SELECT COUNT(r) AS auditMade,
SUM(g.nbrMilkingCows) AS cowsAudited,
AVG(r.gainPerCowPerYearTransition) AS averageGainTransition,
AVG(r.gainPerCowPerYearLactation) AS averageGainLactation,
AVG(r.totalGain) AS averageTotalGain,
AVG(r.supplementalCostPerCow) AS averageSuppCost
FROM `smart_calculator_infos` i
INNER JOIN `smart_calculator_result` r ON r.idSmartCalculatorResult = i.idSmartCalculatorResult
INNER JOIN `calculator_general_informations` g ON g.idSmartCalculatorInfo = i.idSmartCalculatorInfo
WHERE i.idUser = 14
MySQL answers me "Unknown column 'r' in field list".
But I dont really understand why I get an error here as I define r in my INNER JOIN.
I'm kinda new at using SQL so maybe there is something pretty obvious I forgot, but I can't seem to understand what.
You can't count an alias itself, so the very first line of your query is what is causing the error:
SELECT COUNT(r)
To remedy this, you could use COUNT(*):
SELECT COUNT(*)
Or, you could count an actual column in the smart_calculator_result table, e.g.
SELECT COUNT(r.idSmartCalculatorResult)

Why does calling MAX on a subquery fail in SELECT?

Can anyone help me answer why my query returns a syntax error? I'm working on the Hackerrank problem linked here.
Here's the code I wrote:
SELECT MAX(SELECT e1.salary * e1.months FROM Employee as e1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings
I get the following syntax error:
ERROR 1064 (42000) at line 1: 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 'SELECT e1.salary * e1.months FROM Employee
as e1) as max_tot_earnings, COUNT(e.e' at line 1
I know that the subquery doesn't have a syntax error. It runs just fine when run on its own. I was also able to work around the problem, so the purpose of this question is to try and figure out what's going on. I was able to solve the problem with the query shown below:
SELECT (SELECT e1.salary * e1.months as tot_earnings FROM Employee as e1 ORDER BY tot_earnings DESC LIMIT 1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
GROUP BY e.salary, e.months
HAVING e.salary * e.months = max_tot_earnings
I found a few questions here that touch on using SELECT MAX(SELECT ...), but I didn't find answers for the two questions as phrased above. Questions one, two, and three.
In sum, I have two main questions:
Why does the SELECT MAX(SELECT ...) approach return a syntax error? I've used MAX(SELECT ...) statements in HAVING before, so I'm puzzled. Are aggregate functions with subqueries just not allowed in SELECT?
In my search online for an answer to #1, I have seen suggestions move the subquery in the FROM statement. Is this preferable to having the subquery in my SELECT statement (as in my eventual solution shown above)?
The correct syntax is:
SELECT (SELECT MAX(e1.salary * e1.months) FROM Employee as e1) as max_tot_earnings,
COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings;
Or more simply as:
SELECT (e.salary * e.months) as max_tot_earnings, COUNT(*)
FROM Employee
GROUP BY max_tot_earnings
ORDER BY max_tot_earnings DESC
LIMIT 1;
Your query doesn't work for the following reasons:
A subquery needs its own set of parentheses. So does a function call. So MAX( (SELECT . . . ) ) at least meets the parentheses requirements.
The MAX() function takes an argument that is either a column reference or a constant or an expression that evaluates to a scalar. Your function call does not do that.
MAX() doesn't allow subqueries at all, even scalar subqueries.

Query Mysql Error : Not unique table/alias

Can you please help me out. I have this SQL query:
select tenagapengajars.id, tenagapengajars.nama, tenagapengajars.pendidikan, tenagapengajars.created_at, programstudis.nama
from tenagapengajars
LEFT JOIN
tenagapengajars
ON programstudis.id = tenagapengajars.id_prodi
And somehow it says
#1066 - Not unique table/alias: 'tenagapengajars'
You are selecting tenagapengajars and also joining on tenagapengajars. If you want to do that, you have to specify an alias. Otherwise MySQL doesn't know chich table you mean.
from tenagapengajars t1
LEFT JOIN
tenagapengajars t2
You are also selecting data from programstudis, which is not in the query. You probably just copied the wrong table and meant something like:
select tenagapengajars.id, tenagapengajars.nama, tenagapengajars.pendidikan, tenagapengajars.created_at, programstudis.nama
from tenagapengajars
LEFT JOIN
programstudis
ON programstudis.id = tenagapengajars.id_prodi

Join on Join mysql

I am getting an SQL ERROR (1064) Syntax. Is what i am trying to do allowed? As i don't see the syntax error.
`SELECT isc_products.prodname, isc_product_variations.* , isc_product_variation_combinations.vcoptionids,
FROM isc_products
JOIN isc_product_variations
ON isc_products.prodvariationid = isc_product_variations.variationid
JOIN isc_product_variation_combinations
ON isc_product_variation_combinations.vcvariationid = isc_product_variations.variationid`
You have isc_product_variations.variationid twice in your ON statements. Check, if this is what you want, or if there is a second key in you perhaps need isc_product_variations
You have an error on the first line. You have a comma that shouldn't be there:
SELECT isc_products.prodname,
isc_product_variations.* ,
isc_product_variation_combinations.vcoptionids,
-- ^
FROM ...
I'd also advise you not to use SELECT isc_product_variations.* but instead list the columns you want explicitly.

Zend_Db_Select - Joins and Count - Possible Zend Bug?

I'm having an issue getting a COUNT() from a SQL query using Zend_Db_Table_Select, and I think it may be a possible bug because the SQL it should be generating actually works. Here's the Zend Select Query: ($this is a Zend_Db_Table, renamed to table1 in this example)
$select = $this->select();
$select->setIntegrityCheck(false);
// Select Count
$select->from($this, array("COUNT(*) as 'COUNT'"))
->joinLeft('users', 'table1.userID = users.userID')
->joinLeft('table2', 'users.anotherKey = table2.anotherKey');
// Add Where clause after join
$select->where('users.anotherKey = ?', $anotherKeyValue);
This gives the error:
SQLSTATE[42000]: Syntax error or access violation: 1140
Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is
illegal if there is no GROUP BY clause`
However, this query...
SELECT COUNT(*) AS 'count' FROM table1
LEFT JOIN users ON table1.userID = users.userID
LEFT JOIN table2 ON users.anotherKey = table2.anotherKey
WHERE users.anotherKey = [anotherKeyValue]
...returns the expected results with no errors when run against the database. Any ideas whats going on, why the error, and how to get around it?
have you tried to see actual query, that zend_db produce?