I have table in which I have birthdate , age location and Score and I want to retrieve the count of number of records created between two dates where score is not null and there is no time stamp field.
How can I do it if there is no time stamp field.
Is there any meta data and if it is , how can I run the query?
try a query like this:
SELECT COUNT(*)
FROM TABLE_NAME
WHERE BIRTHDATE BETWEEN 'DATE1' AND 'DATE2'
AND SCORE IS NOT NULL AND TIMESTAMP IS NULL;
Add a column timestamp to the existing table, with default value as NULL, and query the above statement, it should work.
Whenever you add a column, to a table already having records, the corresponding values are blank for that new column, for existing records.
Add a timestamp to your tables
Echoed here as other users have noted.
Because you have no date reference field in the database, you can't pull out records that match one or that are between two dates.
Your best bet from here on in, is to add a date field and then make sure when data is written to the DB, you insert a date/datetime using mysql now() function. There are a few different ways to achieve it, but this is probably the easiest:
mysql_query("
INSERT INTO users (first, last, whenadded)
VALUES ('$first', '$last', now())
";
Related
This question already has answers here:
MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?
(3 answers)
Closed 10 months ago.
how can i avoid to add duplicated entry in my database that is based on date? where instead of inserting again the duplicate entry, i will just update the old data to be deactivated and insert the new duplicate entry.
Here is the structure
Price table
id date_created Value is_active
1 2019-10-01 1:00:00 25 0
2 2019-10-05 2:00:00 30 0
but imagine that the user added a duplicated data again for the Price table which is like this.
2019-10-05 3:00:00
so what i want to do is to update the old entry that has the same date of the user entry to be is_active 1 and insert the new entry.
is there a way to do this? doing this on PHP is really complicated for me because of the use of looping, but i think there is a way in MYSQL which i cant figure it out.
You could first try to fetch the entry with the specific date and then update, otherwise insert.
You should also set the date_created column to UNIQUE.
As in the official documentation:
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be
inserted would cause a duplicate value in a UNIQUE index or PRIMARY
KEY, an UPDATE of the old row occurs.
In your case I suggest to you to do these steps:
create a new column date_time_created as DATETIME
convert date_created as DATE and save in it only the date
e.g. $date = date('Y-m-d', strtotime($yourDateTime));
set date_created as UNIQUE index:
CREATE UNIQUE INDEX date_created ON Price(date_created);
INSERT INTO Price
(Value, date_created, date_time_created, is_active)
VALUES
('$theValue', '$date', '$dateTime', 1)
ON DUPLICATE KEY UPDATE is_active = 0
The conversion of date_created in DATE and the creation of date_time_created as DATETIME are necessary because is useless in your case to make a DATETIME unique because you need to check the value only by date. This also improve the readability and maintenance of your script.
Query the table and check if that date exists and is_actice = 1 and use the results to first update existing row then insert
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');
I have one Sql Query to get all the informations from my table.
I created an list using an foreach.
And i want to order this list, by the last updated row.
Like this
$query - "SELECT * FROM table ORDER BY last_updated_row";
//call Query here
And when i updated a certain row, i want to put this row on the top of the list
I heard about time_stamp, can i use time_stamp for that?
how can i do that?
Thanks
Assuming your using MySQL your table needs to be like this
CREATE TABLE table (
last_updated_row TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
That will give the row a create time stamp and update it on each update statement which effects the row
http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
You can use just about any date/datetime/timestamp column in a table to sort by if needed. The only catch is you need to actually have it in the table.
Any of the above will allow sorts by ascending/descending order, but need to be maintained when inserting/updating a row.
Assuming you have the following structure:
table - someTable
id someVale updateTime
1 54634 ......
2 65138 ......
3 94141 ......
4 84351 ......
It doesn't matter what type of column updateTime is - whether it is a date, a datetime, a timestamp, a simple order by updateTime will work.
But you need to make sure that each insert/update you make to that row updates the column so that the sort will be true.
How would I go about adding the current date into the database (MySQL) when a user registers? I know I would need to add a row in the database (Join_date or something), what would I set that to when creating that row? timestamp? varchar?
I want to make it so when the user submits the registration form it adds the current date to the join date row.
Any help would be greatly appreciated.
Thanks.
Suppose structure is
field type
++++++++++++++++++++++
id INT
username varchar(10)
password varchar(10)
date datetime
Then use below query
INSERT INTO Table values (1,'username','password',NOW())
Hope this helps you...
Column type should be datetime
and while inserting row, use NOW() in query
Add a datetime column, and use NOW()doc to set the column when inserting a record.
This was asked many times.
See this question: Registration date . Its solution can be used well; it will automatically insert date.
Add a column TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
Make that field either MySQL internal date/time type (see http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html) and use CURRDATE (http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html) to fill it, or simply make it int and fill it with POSIX time with time().
Personally I find the Unix timestamp better since it's easier to operate and it doesn't depend on the type of db.
You can use a code like this
INSERT INTO users (LastName, FirstName, DateColumn)
VALUES ("firstname", "lastname", NOW())
NOW() would insert the current date in the DateColumn field
try this:
INSERT INTO users (`LastName`, `FirstName`, `DateColumn`)
VALUES ("Fname", "LNamee", NOW())
assuming that you are using mysql, you can use field type DATETIME or TIMESTAMP.
usually I use DATETIME for created ("join date") fields and TIMESTAMP for lastupdated field, since it can be (easily) populated transparently by the RDBMS on update.
To get the current date you can use mysql function NOW().
for example:
INSERT INTO Users (`firstname`, `regdate`) VALUES ('herbie', NOW());
Is there is an easy way to change the following query to check to see if a record already exists for todays date if it does to update it with the newest count value.
mysql_query("INSERT INTO daily_record (PageID, count)
VALUES (".$array['page_id'].",".$array['count'].")");
The column I want to check is a CURRENT_TIMESTAMP field (record_date - part of daily_record table) if a todays date exists for a pageID then an update needs to happen rather than a new insert.
If someone can help that would be amazing!!!
Well if you build the daily_record table like this:
CREATE TABLE daily_record (
pageID INT,
record_date DATE,
count INT,
PRIMARY KEY (pageID,record_date),
INDEX idxPageID (pageID)
)
You could then use the command:
INSERT INTO daily_record (
pageID,record_date,`count`
) VALUES (
1,'2011-03-31',32
) ON DUPLICATE KEY UPDATE `count`=32;
Obviously pageID/record_date/count would be supplied by the calling code. This effectively creates a record for the pageID/day with the given count, or if a record for the pageID/day already exists, then it sets the count to the supplied value.
Using the DATE column type prevents you getting free timestamping BUT that's not particularly useful for this table - the way you describe it - since you don't care about the hours/minutes/seconds.
The key here is the unique index created by the PRIMARY KEY... line. If it's uniqueness would be violated by an insert then an update on it can occur instead.
Best I can come up with is either use a select with if ... then to check for the existance ahead of time, or run the update statement first, check ##rowcount (records affected) and do an insert if it comes back with 0)
i.e. No.
[Edit - this is a little more complex than it seemed at first, because of the DATE thing.]
To UPDATE the record you MUST get the count that you want to update, so that requires you to use a SELECT first. But you need to select the records that are only for the current date.
Let's assume that you have done the code to get the current date into $today.
Then as Kendrick said,
$result=mysql_query("SELECT * from daily_record where PageID=\'$array['page_id']\' and date_field BETWEEN '$today'.' 00:00:00' AND '$today'.' 23:59:59'");
if (!$result)
{ mysql_query("INSERT into daliy_record (PageID,count} VALUES (\'$array['page_id']\',\'$array['count']\')"); }
else
{mysql_query("UPDATE daily_record (count) VALUES (\'$array['count']\') where PageID=\'$array['page_id']\' and date_field=\'$result['date_field']\'");}