How to explode mysql field value and use it in SELECT query - mysql

How can i explode field value of table in select query ?
for e.g. i have 1 field in table named "coordinates" which contains latitude , longitude.
Now i want to use this latitude and longitude in select query.
Can i separate this values and use it in select query ?

Firstly, the comments are correct: this is a violation of normal form. Always store separate data in separate columns - it will make your life easier.
If you try to write a select statement that parses the coordinates field and tries to filter on one or both halves, you will have a query that runs SUPER slowly, since an index on that column will not function. Instead, I would recommend writing a query to split that column into two, such as the following:
alter table `your_table`
add column `coordinate_x` int null;
alter table `your_table`
add column `coordinate_y` int null;
update `your_table`
set `coordinate_x` = substring(`coordinates`,1,locate(',',`coordinates`))
,`coordinate_y`= substring(`coordinates`,locate(',',`coordinates`)+1);
alter table `your_table`
drop column `coordinates`;
alter table `your_table`
modify column `coordinate_x` int not null;
alter table `your_table`
modify column `coordinate_y` int not null;
You could then index coordinate_x and coordinate_y to make your select statement run quickly.

Related

Sum up columns using group by and store as a new column (permanently) in MySQL

I have 50 columns in the MySQL table. I want to sum all these columns and make a new column into the same table (sum50).
This should be stored permanently into the MySQL table whenever I update or insert new data.
I know how to sum up while performing the query but it does not store into the table permanently.
CREATE TRIGGER `name`
AFTER INSERT ON `table`
FOR EACH ROW
UPDATE `table` SET `table`.`coulms` = `table`.`col1`+.... `table`.`col50`+
I am trying the above trigger, but not working.
Should I have a blank column inserted into the table and perform trigger? Which trigger would be correct?
Instead of the trigger, add a generated column to your table:
alter table tablename add(sum50 int generated always as (col1 + col2 + ...) stored);
See a simplified demo.

trying to ALTER a table based on the results from a SELECT statement in mySQL

when i use the following select statement i can return the date differences between date_due and date_returned.
select Date_Due,Date_Returned,
datediff(Date_Due,Date_Returned) as Day_Diff
From tp_rental
However i cant get these values to replace the current null values in the tp_rental table. I tried the below statement also thinking it would create a new column.
alter table tp_rental
ADD DayDiff as DATEDIFF (Date_Due,Date_Returned);
my errors say there is a problem with the syntax near as DATEDIFF
any ideas? thanks in advance
Generated column expressions need to be enclosed in () (see the manual). You also need to add a column type definition:
alter table tp_rental
ADD DayDiff INT as (DATEDIFF(Date_Due,Date_Returned));

"CONCAT"enated column not showing up in database table

I tried concat function to combine two columns, i got the output also but
my question is why i don't see new column being added to the table. Is concatenating is just a temporary result?
SELECT CONCAT(Name,',',Continent)AS new_address FROM Country
If you want to add a column to the table, you need to alter the table:
alter table country add new_address varchar(255);
Then you can set the value using update:
update country
set new_address = concat_ws(' ', name, continent);
I prefer concat_ws() for this type of operation because it does not return NULL if one of the columns is NULL.
Note: The table has the "correct" values after the update. But, subsequent changes to the table might require that you re-run the update or that you use a trigger to maintain consistency.
On best practice is to define a view to do the calculation:
create view v_country as
select c.*, concat_ws(' ', name, continent) as new_address
from country;
When you access the data through the view, the new_address field will always be correct.
Yes this creates a column that only exists in your SELECT query.
It certainly does not alter the underlying table.
If you wanted to add this computation to the underlying table you could add a generated column as of MySQL 5.7.6.
CREATE TABLE Country
(
Name VARCHAR(100) NOT NULL,
Continent VARCHAR(100) NOT NULL
);
INSERT INTO Country
VALUES ('France', 'Europe'),
('Nigeria','Africa');
ALTER TABLE Country
ADD new_address VARCHAR(201) AS (CONCAT(Name,',',Continent));
SELECT *
FROM Country;
Online Demo

Store records in a new table created by a query in mysql

I have two tables ,location and locationdata. I want to query data from both the tables using join and to store the result in a new table(locationCreatedNew) which is not already present in the MySQL.Can I do this in MySQL?
SELECT location.id,locationdata.name INTO locationCreatedNew FROM
location RIGHT JOIN locationdata ON
location.id=locationdata.location_location_id;
Your sample code in OP is syntax in SQL Server, the counter part of that in MySQL is something like:
CREATE TABLE locationCreatedNew
SELECT * FROM location RIGHT JOIN locationdata
ON location.id=locationdata.location_location_id;
Referance: CREATE TABLE ... SELECT
For CREATE TABLE ... SELECT, the destination table does not preserve information about whether columns in the selected-from table are generated columns. The SELECT part of the statement cannot assign values to generated columns in the destination table.
Some conversion of data types might occur. For example, the AUTO_INCREMENT attribute is not preserved, and VARCHAR columns can become CHAR columns. Retrained attributes are NULL (or NOT NULL) and, for those columns that have them, CHARACTER SET, COLLATION, COMMENT, and the DEFAULT clause.
When creating a table with CREATE TABLE ... SELECT, make sure to alias any function calls or expressions in the query. If you do not, the CREATE statement might fail or result in undesirable column names.
CREATE TABLE newTbl
SELECT tbl1.clm, COUNT(tbl2.tbl1_id) AS number_of_recs_tbl2
FROM tbl1 LEFT JOIN tbl2 ON tbl1.id = tbl2.tbl1_id
GROUP BY tbl1.id;
NOTE: newTbl is the name of the new table you want to create. You can use SELECT * FROM othertable which is the query that returns the data the table should be created from.
You can also explicitly specify the data type for a column in the created table:
CREATE TABLE foo (a TINYINT NOT NULL) SELECT b+1 AS a FROM bar;
For CREATE TABLE ... SELECT, if IF NOT EXISTS is given and the target table exists, nothing is inserted into the destination table, and the statement is not logged.
To ensure that the binary log can be used to re-create the original tables, MySQL does not permit concurrent inserts during CREATE TABLE ... SELECT.
You cannot use FOR UPDATE as part of the SELECT in a statement such as CREATE TABLE new_table SELECT ... FROM old_table .... If you attempt to do so, the statement fails.
Please check it for more. Hope this help you.
Use Query like below.
create table new_tbl as
select col1, col2, col3 from old_tbl t1, old_tbl t2
where condition;

Use select to create new column names - MYSQL

I am trying to figure out how to write one statement where I can grab a value with a select statement and use that value to create a new column. for example:
SELECT CONCAT( SUBSTRING(latestfile.short_filename,6,5),'_m')
FROM latestfile
LIMIT 9,1
this gets me the value I want
then almost "add" it to this type of statement:
ALTER TABLE `latestfile`
ADD `newvaluefromaboveselectstatement` VARCHAR( 35 ) NULL DEFAULT NULL
My select statement above is specifically pulling position "9,1" I really want to do this for "8,1" then 7,1, then 6,1 etc.
Is this possible?