How to alias a field or column in MySQL? - mysql

I'm trying to do something like this. But I get an unknown column error:
SELECT SUM(field1 + field2) AS col1, col1 + field3 AS col3 from core
Basically, I want to just use the alias so that I won't need to perform the operations performed earlier. Is this possible in mysql?

select #code:= SUM(field1 + field2), #code+1 from abc;
But, please be aware of the following (from the MySQL 5.6 docs):
As a general rule, other than in SET statements, you should never assign a value to a user variable and read the value within the same statement. For example, to increment a variable, this is okay:
SET #a = #a + 1;
For other statements, such as SELECT, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate #a first and then do an assignment second:
SELECT #a, #a:=#a+1, ...;
However, the order of evaluation for expressions involving user variables is undefined.
So, use at your own risk.

Consider using a subquery, like:
SELECT col1
, col1 + field3 AS col3
FROM (
SELECT field1 + field2 as col1
, field3
from core
) as SubQueryAlias

You can select the alias:
SELECT SUM(field1 + field2) AS col1, (select col1) + field3 AS col3 from core
This works.

select #code:= SUM(field1 + field2), (#code*1) from abc;
#code*1 covert into numeric expression and you can use anywhere like
select #code:= SUM(field1 + field2), (#code*1)+field3 from abc;

Short answer is no:
mysql> select 1 as a, a + 1 as b;
ERROR 1054 (42S22): Unknown column 'a' in 'field list'
postgresql# select 1 as a, a + 1 as b;
ERROR: column "a" does not exist
That said, some SQL implementations allow to use the aliases in where/group by/having clauses, e.g.:
postgresql# select 1 as a group by a; -- 1 row

In case you are using it with aggregate function (group by) and if it doesn't work for you place the calculated column to the end with forward column referecing.
SELECT FNC2(AF), FNC1(A) AS AF, B, C, FROM Table GROUP BY ...
1st one doesn't work due to forward column referencing. Do this instead
SELECT FNC1(A) AS AF, B, C, FNC2((SELECT AF)) FROM Table GROUP BY ...

Related

How do I execute a query using INSERT INTO and WITH statement?

INSERT INTO tablename( columnname1, columnname2, columnaname2)
WITH
a AS
SELECT * FROM tablename
WHERE condition
),
b AS
SELECT * FROM tablename
WHERE condition
)
I have a couple lines of query below where I use an DISTINCT statement but would like to know for now whether my query above is correct or not.
WITH? This is going to be introduced in MySQL 8.0. Are you using a preview release? Otherwise you won't be able to use WITH in MySQL.
Anyway: A WITH clause belongs at the beginning of the statement: WITH ... INSERT .... See here: https://dev.mysql.com/doc/refman/8.0/en/with.html.
It seems, however, you are not even using your CTEs a and b. Your CTEs are also lacking parentheses. Your statement should look something like this for instance:
WITH a AS (SELECT * FROM tablename WHERE condition)
, b AS (SELECT * FROM tablename WHERE condition)
INSERT INTO tablename(columnname1, columnname2, columnaname2)
SELECT col1, col2, col3 FROM a
UNION ALL
SELECT col1, col2, col3 FROM b;

mysql aggregate function for varchar column

I need to calculate the sum of one column(col2) , but the column has both numbers and text. How do I exclude the text alone before I use sum()?
The table has around 1 million rows, so is there any way other than replacing the text first?
My query will be :
Select col1,sum(col2) from t1 group by col1,col2
Thanks in advance
You can use regexp to filter the column:
Select col1,sum(col2) from t1 WHERE col2 REGEXP '^[0-9]+$' group by col1,col2
You could use MySQL built in REGEXP function.
to learn more visit : https://dev.mysql.com/doc/refman/5.1/en/regexp.html
Or another way is using CAST or CONVERT function
to learn in detail : https://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
Hope this is helpful
Assuming you mean the number is at the beginning of the tex, the easiest way is simply to use implicit conversion:
Select col1, sum(col2 + 0)
from t1
group by col1, col2;
If col2 starts with a non-numeric character, then MySQL will return 0. Otherwise, it will convert the leading numeric characters to a number.
Note that your query doesn't really make sense, because you are aggregating by col2 as well as including it in the group by. I suspect you really want:
Select col1, sum(col2 + 0)
from t1
group by col1;

MySQL declare a user defined variable inside select statement but do not show it as column

I'm constructing a select statement that will later be the value of an insert statement.
Most of the columns will be calculated fields. I recently learned that you can reuse calculated fields during select:
select
id,
#sum1 := col1 + col2 as colSum1,
#total1 := #sum1 + col3 as colTotal1,
#gtotal := #sum1 + total1 as colGTotal
the result set will be 4 columns: id, colSum1, colTotal1, and colGTotal.
I need the resulting column to be just the last column colGTotal.
Again this select statement will be a value of an insert.
INSERT INTO tbltest VALUES (SELECT...)
I just need to insert the colGTotal
So I guess what I need is variable declaration and assignment inside the select statement (can't be outside) but EXCLUDE it as one of the resulting columns to be fed on the insert statement.
If you can, rewrite your query to yield a single column:
select col1 + col2 + col1 + col2 + col3 as colGTotal
alternatively, you can can use this SELECT statement as a subquery, and SELECT just the column you want on it:
INSERT INTO tbltest VALUES (SELECT colGTotal FROM (SELECT id, #sum1 ...) AS foo)

reuse "sum(table_column) as x"

I have a problem with an SQL query.
SELECT SUM(table_colum) AS value, SUM(value * 3) AS value2 FROM table;
You need to know this is a short representation of my whole query.
The error:
Unknown column 'value' in 'field list'
Is there a way to reuse value in another SUM()?
You can just do:
SELECT SUM(table_colum) AS value, SUM(SUM(table_colum) * 3) AS value2 FROM table;
Internally, the server will only do the SUM(table_colum) calculation once and use the result twice.
I suppose you could write
SELECT value, SUM(value * 3) AS value2
FROM ( SELECT SUM(table_column) AS value
FROM table
) AS t
;
But as I mentioned in a comment above, I'm not sure what you would want this for. SUM(table_column) is just a single value, so the SUM of it is just the same value. So you'd get the same result by writing:
SELECT value, value * 3 AS value2
FROM ( SELECT SUM(table_column) AS value
FROM table
) AS t
;
without the second SUM.

mysql and or query together

How can i run mysql and or query together instant of separate query.
e.g.:
And query:
select * form tablename where name='A' and password="A" and id='A';
Or query:
select * form tablename where name='A' or password="A" or id='A';
-These are 2 different query,can i make these query together?what is the syntax??
Use parentheses to group the conditions?
SELECT * FROM table WHERE (X and Y or Z) AND (P and Q or F)
Well, you can just union them but, since one is a subset of the other, it's not strictly necessary:
select * from tablename
where name = 'A' and password = 'A' and id = 'A'
union select * from tablename
where name = 'A' or password = 'A' or id = 'A'
That will give you exactly the same results as if you had just run the second query on its own. That will make sense once you realise that every single row from the first query has a name equal to 'A', so it will match the first part of the where clause in the second query.
If you want duplicate rows for those returned in both queries, just use union all instead of union.
If you were using 'A' as just a placeholder and its values are different in the two queries, then you have two approaches. Use a construct like:
... where (name = 'A' and password = 'B' and id = 'C')
or name = 'D' or password = 'E' or id = 'F'
or use the union solution I gave above, something like:
select * from tablename
where name = 'A' and password = 'B' and id = 'C'
union select * from tablename
where name = 'D' or password = 'E' or id = 'F'
(use union all when you know there is no possibility of duplicates between the two queries, - it will save the DBMS the trouble of removing non-existent duplicates - that's not the case with these queries).
The union may give better performance on a DBMS that can hive off the two selects more easily to separate query engines (something that would be more difficult with a single query with a complex where clause). Of course, as will all optimisations, measure, don't guess.
It is not clear what you expect as the result, but my guess is you want a UNION:
SELECT 1 `query`, `name`, `password`, `id`
FROM `tablename` WHERE `name`='A' and `password`='A' and `id`='A'
UNION
SELECT 2 `query`, `name`, `password`, `id`
FROM `tablename` WHERE `name`='A' or `password`='A' or `id`='A'
Note that the first column query in result is required to separate results from the two queries because union of (X and Y) and (X or Y) is always (X or Y).
Use () for such type of conditions
select * form tablename
where name='A' OR password="A" OR id='A' OR
(name='A' AND password="A" AND id='A')
If you want to check for same string as A here then you will get same o/p using following query
select * form tablename
where name='A' OR password="A" OR id='A'
Just combine the conditions with WHERE
SELECT * FROM tablename WHERE (name='A' AND password='A' AND id='A') OR name='A' OR password='A' OR id='A'
The parentheses ensure that the whole AND expressions "validates" only if ALL the containing conditions are true while the rest macthes the OR