MySQL. Queries. Unknown column [duplicate] - mysql

This question already has answers here:
Unknown Column In Where Clause
(16 answers)
Closed 8 years ago.
I have this following query and I want to display the results where masini > 2 but when I run the query it says that 'masini' is not an existing column but it's the name of a custom column I defined on the first row. I am new to MySQL.. can anyone point me in the right direction?
This is my query:
SELECT pers.serie_buletin AS persoana, COUNT(prop.serie_buletin) AS masini
FROM persoana pers
JOIN proprietate prop
ON pers.id_persoana = prop.serie_buletin
WHERE masini > 2
GROUP BY persoana ;
I defined the column on this line, in this part "COUNT(prop.serie_buletin) AS masini" but it says "Error Code: 1054. Unknown column 'masini' in 'where clause'". What am I missing?

Change WHERE to HAVING.
GROUP BY persoana
HAVING masini > 2;
The MySQL HAVING clause is used in the SELECT statement to specify
filter conditions for group of rows or aggregates.
The MySQL HAVING clause is often used with the GROUP BY clause. When
using with the GROUP BY clause, you can apply a filter condition to
the columns that appear in the GROUP BY clause. If the GROUP BY clause
is omitted, the MySQL HAVING clause behaves like the WHERE clause.
Notice that the MySQL HAVING clause applies the condition to each
group of rows, while the WHERE clause applies the condition to each
individual row.
source

The where clause is evaluated first, so MySQL don't know what is masini there. Here are some similar questions.
Getting unknown column error when using 'as' in mysql statement
Unknown Column In Where Clause
As explained in the questions above and another answers here, you can only use alias from sub-queries, or in clauses that are evaluated after the alias is assigned as ORDER BY, GROUP BY or HAVING, in your case you can use the having clause.

SELECT pers.serie_buletin AS persoana,
COUNT(prop.serie_buletin) AS masini
FROM persoana pers
JOIN proprietate prop
ON pers.id_persoana = prop.serie_buletin
GROUP BY pers.serie_buletin
HAVING COUNT(prop.serie_buletin) > 2;

You can't put column aliases in the where clause. Ever.
In this case, though, you actually need a having clause:
SELECT pers.serie_buletin AS persoana, COUNT(prop.serie_buletin) AS masini
FROM persoana pers
JOIN proprietate prop
ON pers.id_persoana = prop.serie_buletin
GROUP BY persoana
HAVING masini > 2;

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)

have any SQL GROUP_CONCAT alternative function?

here i was past my sql query.
any body know GROUP_CONCAT alternative function so let me know ?
SQL Error :
<h1>A Database Error Occurred</h1>
<p>Error Number: 1140</p>
<p>In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'smartsaver.ud.id'; this is incompatible with sql_mode=only_full_group_by</p>
SQL Command :
SELECT ud.id, ud.url, d.document_name, d.d
GROUP_CONCAT(LEFT(REPLACE(url, "document", "thumb"), CHAR_LENGTH(REPLACE(url, "document", "thumb")) - LOCATE(".", REVERSE(REPLACE(url, "document", "thumb")))), ".", "png")
ud.document_url
END as new_url, CASE WHEN ud.type = 1 THEN "Image" WHEN ud.type = 2 THEN "Video" WHEN ud.type = 3 THEN "File" WHEN ud.type = 4 THEN "Text" ELSE "" END as type, d.added_on, ud.type as document_type
FROM tbl_uplaod_document ud
JOIN tbl_document d ON d.id = ud.document_id
LEFT OUTER JOIN tbl_document_project_relation pr
ON pr.document_id = ud.document_id
WHERE ud.is_active = 1
AND d.is_active = 1
AND ud.user_id = 1
AND ud.document_id = 116
LIMIT 10
#dev5 Your code to hard to read
Expression #1 of SELECT list is not in GROUP BY clause and contains non aggregated column 'smartsaver.ud.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by.
will be simply solved by changing the sql mode in MySQL by this command:
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));
Thank You :-)
You have a select with an aggregation function. That makes the query an aggregation function. But there is no group by. Happily, MySQL now generally returns an error in this case.
Earlier versions of MySQL allowed a malformed query such as your using the default settings. It would return values for the unaggregated columns from arbitrary rows. The default settings have changed to generate an error.
You should add a group by for all non-aggregated columns in the select:
group by ud.id, ud.url, d.document_name, d.d, . . .
Your code is rather hard to read, so it is hard to pick out the unaggregated columns.

Rewrite the SQL in version 5.7

I have a following SQL which works in mysql version 5.6 but is breaking in mysql version 5.7.x.
SELECT * FROM (SELECT * FROM photos WHERE photoable_type = 'Mobilehome'
AND photoable_id IN (SELECT id FROM mobilehomes WHERE
mobilehomes.community_id = 1) AND photos.image_file_size IS NOT NULL
AND photos.is_published IS TRUE ORDER BY photos.priority ASC) AS tmp_table
GROUP BY photoable_id
It's throwing me following error:
Expression #1 of SELECT list is not in GROUP BY clause and contains
nonaggregated column 'tmp_table.id' which is not functionally
dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by
In this case or you change the sql mode for instrcut the db to work as mysql 5.6 version or you can adeguate your query to the new behavior
In this second case
If you use group by whithout aggregation function this mean that for all the column different from photoable_id you accept casual result
This mean that you could, probably, also accepted an aggregated result based greagtion function eg: on min() or max ()
assuming your tables containg col1, col2, .. the you must declare explicitally the column you need
SELECT photos.photoable_id, min(col1), min(col2),....
FROM photos
INNER JOIN mobilehomes ON mobilehomes.community_id = 1
AND photos.photoable_type = 'Mobilehome'
AND photos.photoable_id = mobilehomes.id
AND photos.image_file_size IS NOT NULL
AND photos.is_published IS TRUE
GROUP BY photos.photoable_id
ORDER BY photos.priority ASC
Looking to your code seems also that you could avoid the subquery

Prestashop - List view filter

I insert an other column in the list view of my module inserting the values with getList function, I modified the sql to filter in the renderList function but I can't use the alias in where clause.
How can I fix it?
The error i got is the next:
Uncaught Unknown column 'product_supplier_name' in 'where clause'<br /><br />
SELECT SQL_CALC_FOUND_ROWS a.* , s.name AS product_supplier_name FROM ps_supplier_bill a LEFT JOIN ps_supplier s ON s.id_supplier = a.id_product_supplier WHERE 1 AND product_supplier_name LIKE '%fa%' ORDER BY product_supplier_name asc LIMIT 0,50
The proper query should be this:
SELECT SQL_CALC_FOUND_ROWS a.* , s.`name` AS product_supplier_name FROM `ps_supplier_bill` a LEFT JOIN `ps_supplier` s ON s.`id_supplier` = a.`id_product_supplier` WHERE 1 AND s.`name` LIKE '%fa%' ORDER BY s.`name` asc LIMIT 0,50
It's not possible use directly an alias in WHERE, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain. REFER
From MySQL doc:
Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined.
MySQL doc

How can I execute the MSSQL query without error?

I'm trying to execute mssql query but its showing error.The same query I executed in MySQL its working fine.
The Query is:
SELECT tst_flow_name, tst_flow_desc,COUNT(tst_flow) tot
FROM test_flow_details
LEFT OUTER JOIN tst_flow ON tst_flow_name=tst_flow
AND test_flow_details.project=tst_flow.project
WHERE test_flow_details.project='JupiterQA'
ERROR IS:
Column 'test_flow_details.tst_flow_name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
How can I execute the MSSQL query without error.
You can't mix normal column selects with aggregate function call like count().
Group by the columns you want to be unique and then you can add count()
SELECT tst_flow_name, tst_flow_desc, COUNT(*) tot
FROM test_flow_details
LEFT OUTER JOIN tst_flow ON tst_flow_name=tst_flow
AND test_flow_details.project=tst_flow.project
WHERE test_flow_details.project='JupiterQA'
GROUP BY tst_flow_name, tst_flow_desc