MySQL replace field entry with substring [duplicate] - php

This question already has answers here:
Converting a date in MySQL from string field
(4 answers)
Closed 9 years ago.
I currently have dates stored in my database (in string format) currently as mm/dd/yyyy.
I need to replace all entries as yyyy/mm/dd for sorting purposes.
To clarify, I am a PHP developer but my raw MySql isnt as strong. I was thinking of doing this by using substrings to re-arrange the date. (I tried in PHP first but it take way too long to process this much data, about a half million rows).
Am i going about this correctly? if so, how do I "loop through" the data, assigning my substr variables for the current iteration?
Note: I did try str_to_date here and it ended up nullifying half of the fields. Im not entirely sure why.
Your help is greatly appreciated.

this is an insert statment
INSERT INTO yourtable (datefield) VALUES (str_to_date(date, '%Y/%m/%d'));
and this an update
UPDATE Table SET date=STR_TO_DATE('date','%Y/%m/%d')
try this
UPDATE Table SET date = DATE_FORMAT('date', %Y/%m/$d);

I believe this will work if your column is in a consistent mm/dd/yyyy format
UPDATE mytable
SET date = CONCAT(right(date,4), '/', left(date,5))

Related

Get data from database using date groups in laravel [duplicate]

This question already has answers here:
Laravel Eloquent get results grouped by days
(17 answers)
Closed 2 years ago.
I am using laravel and I am trying to get data from database grouped by the column "created_at".
The data into created_at column is being stored is in the below format,
2020-07-23 07:03:59
My question is , how can we fetch the data using group for dates only.
For example , All the records should be grouped into one array/object with same dates.
I tried executing the following query,
$transactions= MyTransaction::where('id','=',$user->id)->orderBy('created_at')->get()->groupBy(function($item) {
return $item->created_at->format('Y-m-d');
});
but it does not return what i am expecting, it considers the seconds and hours into the consideration too.
Please guide me solving this query.
$column = \DB::raw("CONCAT(YEAR(`ride_date`),'-',MONTH(`ride_date`),'-',DAY(`ride_date`)) AS `group_column`");
$transactions= MyTransaction::select('*',$column)->where('id','=',$user->id)->orderBy('created_at')->groupBy('group_column')->get();

mysql/mariadb date column time add to get total time [duplicate]

This question already has answers here:
MySQL - How to SUM times?
(5 answers)
Closed 5 years ago.
I am working on a check in out front desk register and hit a wall when attempting to add the total times for all visits by individuals or companies: when i run the following query:
$yearStart = date('Y-m-d', strtotime(date('Y-01-01')));
$today = date("Y-m-d",time());
$sql = "SELECT visCompany, count(visCompany) as accumilatedVisits, sum(timeVisited) as total_time from cards where cards.dateOfVisit BETWEEN '$yearStart' AND '$today' GROUP BY cards.visCompany ORDER BY accumilatedVisits DESC";
I get the sum of the two numbers but not in the correct format, but I cannot figure or find a better way to do it... I had at the start the following times saved in my Cards table: 00:29:18 and 00:05:43 which when added together give me 3461 which would be correct-ish if you put a space between 34 and 61, the total should be 00:35:01 and the values seem to be there but i would think that there is a cleaner way of accomplishing the correctly added and formatted values... I have been scowering the mariadb kb and even trying to find the solution here... I would be okay figuring out a way to do the formatting and the minute correction in php too.. but would prefer to use sql to get the desired result.
Any one have any suggestions?
Whops i put a duplicate... found the answer:: MySQL - How to SUM times?
my new query:: SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(cards.timeVisited))) as total_time_visited FROM cards;
tested and worked with the result being 00:35:01.
Sorry about the duplicate... And thanks for reading.

Prevent INSERT if time overlap in PgSQL without trigger [duplicate]

This question already has an answer here:
Postgres constraint for unique datetime range
(1 answer)
Closed 7 years ago.
i would like to prevent an insert into my PgSQL table if the values for a time period (lets call them newStart and newEnd), if this would overlap with any other timeperiod in my rows.
So, the table has a bunch of row where each has a start and end date (oldStart and oldEnd).
Is it possible to do this inside the query, without an trigger, an without getting all the data from the db first end check it inside php (because i think this is not ne best/fastest way to do).
Please correct me i think wrong.
I found the PgSQL overlap function, but building a query was not possible for me! How can i get more in touch with advanced database things? Just by doing?
Use an exclusion constraint.
More elegant with actual range types instead of start/end:
Preventing adjacent/overlapping entries with EXCLUDE in PostgreSQL
But you can also use an expression in the constraint. Basically:
CREATE TABLE tbl (
tbl_id serial PRIMARY KEY
, starts_at timestamp
, ends_at timestamp
, EXCLUDE USING gist (tsrange(starts_at, ends_at) WITH &&) -- no overlapping
);
More details:
Postgres constraint for unique datetime range
How can I get more in touch with advanced database things?
Study answers here, read the excellent manual, experiment with newly found techniques.

How to get the number of next increment in mssql in php? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get Insert id in MSSQL in PHP?
I MYSQL I would do
SHOW TABLE STATUS LIKE 'image'
In mssql, sigh, I've no idea how to do it...
Please advice.. :)
You can try this to get the NEXT identity.
SELECT IDENT_CURRENT('image') + IDENT_INCR('image')
You can use this:
SELECT IDENT_CURRENT ('image')
then add 1 to get the next.
It's better than using max(id)+1 because the latest id might have been deleted
You could use the max value +1. Something like
Select max(id)+1 from image;

Best way to search a comma separated mysql field

I have been given the task to combine 2 mysql fields into one and then make it so that the new field can be searched. The 2 fields I had to combine in my database where previous year registered and current years registered. The format both these fields are in are dd/mm/yyyy. I have combined these fields into a field called Years Registered whih is still in the same format dd/mm/yyyy but has the years registered seperated by a comma(,). I am wondering how I would go about performing a couple different kinds of querys on this column. The mysql queries I have to perform are: Show All() , Show All between dates: mm/yyyy and mm/yyyy , Before: mm/yyyy , After: mm/yyyy
Any help would be greatly appreciated.
Thanks for your time.
I don't like it but if you need you can use the next solution:
extract date using start_date = STR_TO_DATE(SUBSTRING(your_new_field, 1, 10))
and end_date=STR_TO_DATE(SUBSTRING(your_new_field, 12, 10))
Do not do this!
I do not know how it is exactly possible (some SQL Stringoperations and Datefunctions in a storedprocedurem i presume), but it will surely kill performance of your database.
use a relation for this.
This is:
way faster
more expandable (eg. for three dates..)
easier to code
much better understandable
more portable to other databases
If you have problems with existing platforms you have to support, use a code base where both alternatives are supported. This is still easier and better to maintain than to use a comma-separated list
Your database would be breaking 'First Normalized Form (1NF)' and would be highly ineffecient.
In order to search for a selected date, you would either have to query all rows in the table, or use LIKE which is also very sluggish.
Whoever is asking you to do this should read this article on database normalization.
What is wrong with using two DATE, or DATETIME fields and the formatting them outside of MySQL?

Categories