Add new column into mysql from another column from select statement - php

I have a datetime() column date_time in my database.
I need to convert this to date() and create a new temporary column date_field till the session ends.
I've tried this:
$query1 = SELECT date_time, date(date_time) as date_field FROM table_name....
This works and creates a temp column date_field with all the date values for the date_time field
Problem : This only works for this query. I also have another query which searches for date_time field and thus results into a DB error Unknown field 'date_field'.
$query2 = SELECT date_field FROM table_name
| This table doesn't have date_field as a column
Can this field be created so that I can use this for a time till the session ends ? as we do for temporary tables ?
Note: I can't use ALTER to add new column here due to code limitations.
Any ideas ?
Thanks!

In the first query, you dont really create any column, you just return a a column (date_time), run some function on it (date()) and give it an alias name (date_field). This happens only in the result set, and abvioysly cant be used outside of this query.
What you need to do is simply use the same in the second query: instead of select date field you need select date(date_time) as date_field

Related

date between in mysql not correctly working

when I fetch data from table "like date from 01/09/2017 to 30/09/2017" then it's okey..
BUT When I am trying to fetch data from date 01/09/2017 to 01/10/2017 then its only showing the data of DATE 01/10/2017(not previous month data i.e 01/09/2017)
I am using MySQL Database.
SELECT * FROM `tablename` where date between '01/09/2017' AND '01/10/2017'
If you are saving the value as DATE format it should work. If not (you are saving the data as VARCHAR you can convert it to date and get the correct results.
STR_TO_DATE('01/09/2017', '%m/%d/%Y')
You need to store dates as DATE type not VARCHAR or TEXT.
Also DB dates are in the format YYYY-MM-DD usually so you will need to adjust your query accordingly.
Due to speed trying to use STR_TO_DATE is a terrible idea, better to convert once and then use MySQL as intended.
Backup your data first and then I (think) the following will work
BEGIN;
ALTER TABLE `tablename`
ADD COLUMN `new_date` DATE;
UPDATE `tablename`
SET `new_date` = STR_TO_DATE(`date`, '%d/%m/%Y');
ALTER TABLE `tablename`
DROP COLUMN `date`;
ALTER TABLE `tablename`
CHANGE COLUMN `new_date` `date` DATE;
COMMIT;
Step By Step -
Add an extra column to store the data temporarily
Update the table and copy the current date column value (formatted
DB friendly date) into the new temp column.
Remove the old column
Change the column name to the previous name so all existing queries work.
Then your query is as simple as
SELECT * FROM `tablename` where date between '2017-09-01' AND '2017-10-01'
According to your example you have stored date as text so you need to apply STR_TO_DATE() to perform date operations
Try below query:
SELECT * FROM `tablename` where STR_TO_DATE(date,'%d/%m/%Y')between
STR_TO_DATE('01/09/2017','%d/%m/%Y') AND STR_TO_DATE('01/10/2017','%d/%m/%Y');

Selecting multiple tables and displaying them ordered by datetime column

I want to display the logs to recent activities page ordered by date. Now I was trying to execute this to my mysql
"SELECT * FROM tracking_log.editlog, tracking_log.deletelog, tracking_log.loginlog, tracking_log.logoutlog ORDER BY time ASC";
but it always says
Column 'time' in order clause is ambiguous
all of the tables have a time column, format by datetime (0000-00-00 00:00:00)
How am I going to fetch them ordered by time?
Thanks in advance!
By which table's time column you want to order?
Assuming you want to order the result set by tracking_log.editlog.time column then the query would look like below:
SELECT
*
FROM tracking_log.editlog, tracking_log.deletelog,
tracking_log.loginlog, tracking_log.logoutlog
ORDER BY tracking_log.editlog.time ASC;
Just in case if all of the time columns in the respective table don't contain NOT NULL values at the same time then you need to use COALESCE I guess.
Query using COALESCE
SELECT
*
FROM tracking_log.editlog, tracking_log.deletelog,
tracking_log.loginlog, tracking_log.logoutlog
ORDER BY
COALESCE(tracking_log.editlog.time , tracking_log.deletelog.time, tracking_log.loginlog.time,tracking_log.logoutlog.time) ASC;
'tracking_log' is your database name, and you're selecting multiple tables from that database, so you need to specify from which table you want to order 'time' by:
select * from tracking_log.editlog, tracking_log.deletelog ORDER BY tracking_log.editlog.time ASC
or whichever table from your database you want to use 'time' from. This will fix the error but won't return any results because you have multiple tables in a SELECT clause without anything relating them together.
You'll need to specify some common columns on which you want to return results rather than getting the wildcard and then UNION the tables to aggregate the results. For example, if you have common columns userID, description and time in all your tables, you could do the following:
(SELECT userID, description, time FROM tracking_log.editlog)
UNION
(SELECT userID, description, time FROM tracking_log.deletelog)
ORDER BY time

Mysql Select data and time

Well i writing betting script got all data in mysql
Table Games row BetillDate row BetillTime
BetillDate| BetillTime
--------------------
2015-01-21|15:00:00|
2015-01-29|15:00:00|
2015-01-27|15:00:00|
How to Mysql Select Date its today and time its now in one select...
This select not working right ..
SELECT DISTINCT
class.`name`
FROM
class
INNER JOIN market ON class.game_id = market.class_id
WHERE
market.betTillDate > NOW() AND
market.betTillTime > NOW()
or if its not possible how can i do it?
Thanks!
I suggest fixing the database by adding a field of DATETIME type and concatenating those two fields into it.
Alter table TABLEX add BetillDateTime DATETIME;
Update TABLEX set BetillDateTime = TIMESTAMP(CONCAT(BetillDate,' ',BetillTime));
Now you have a single field for both date and time, and should fix your code to use only that one, then later drop the other two.
And now all you need in the where clause is:
WHERE market.BetillDateTime > NOW()
SELECT DISTINCT
class.`name`
FROM
class
INNER JOIN market ON class.game_id = market.class_id
WHERE
TIMESTAMP(market.betTillDate,market.betTillTime) > NOW()

extracting and inserting data from a query into a column on the same table error

I have this query
"SELECT STR_TO_DATE(TIME(mytimestamp), '%H:%i:%s') As time FROM ". $this->table_name;"
that extracts the time from the column timestamp. I tried inserting it into a column called time called timestamp using the following query
INSERT INTO admin_tmp (time) SELECT STR_TO_DATE(TIME(mytimestamp), '%H:%i:%s')
but I get the error
"INSERT INTO admin_tmp (time) SELECT STR_TO_DATE(TIME(mytimestamp), '%H:%i:%s')"
The mytimestamp does exist and the first query works so I am confused on how to insert it into another column
Why not use update command if its on the same table
update your_table_name
set
time = STR_TO_DATE(TIME(mytimestamp), '%H:%i:%s');

MYSQL Select between date breaking on year

I have created a simple form which users submit. Everything works great but I recently found that the
SELECT * FROM `Forms` WHERE `Date` BETWEEN '{$startDate}' AND '{$endDate}'
The column Date is type TEXT. I needed it to be text cause I thought it would be easier to display everything in MM/DD/YY format. Now I dont want to risk changing the data type since the form is working fine.
Example of Date column
01-03-2013
01-04-2013
07-25-2012
08-01-2012
08-01-2012
08-01-2012
08-01-2012
Ex of working Query
SELECT * FROM `Forms` Where `Date` Between '01-08-2012' and '12-12-2012'
Ex of not working Query
SELECT * FROM `Forms` Where `Date` Between '01-08-2012' and '01-04-2013'
Any reason why it would break if the year changes? How can I get it to work even if the year changes.
you can do it like that
SELECT * FROM `Forms`
WHERE str_to_date(`Date`, '%d-%m-%Y') BETWEEN '2012-01-30' AND '2013-09-29'
DEMO HERE
EDIT :
if you want fix your table here how you do
Add a new column of the appropriate DATE data type:
ALTER TABLE `Forms` ADD `new_date` DATE AFTER `Date`;
Use MySQL's STR_TO_DATE() function to populate that new column with the dates held in the old column:
UPDATE `Forms` SET `new_date` = STR_TO_DATE(`Date`, '%d-%m-%Y');
Drop the old column (and, if so desired, rename the new one in its place):
ALTER TABLE `Forms` DROP `Date`, CHANGE `new_date` `Date` DATE;
Change your application to use this new column.
Because your column is a TEXT column MySQL will use an alphabetic compare.
01-08 comes before 01-04 so it's actually the month part already that breaks.
To fix this, either convert the column to a DATE type or reverse the order of the date to YYYY-MM-DD, in both cases the BETWEEN should function correctly.
Try this::
SELECT * FROM `Forms` Where str_to_date(`Date`, '%d/%m/%Y') Between '01-08-2012' and '12-12-2012'
If you are worried about it breaking then export the database then make the change. You won't get what you expect because it is a TEXT field not a date field. MySQL is sorting per character. As in it is looking at the first character then the next then the next.
Like navnav said it won't break but make a backup just encase.
As for displaying only the date you can explode() on a space to get only the date:
<?php
list($date, $time) = explode(" ", $datetime, 2);
echo $date;
?>
try this:
select * from "forms" where Date('column_name') between '' and ''

Categories