SQL ignores 2nd criterion in WHERE clause - mysql

Why would the second criterion in this WHERE clause be ignored?
$old = time() - 2592000;
$sql_deleteold = ("DELETE FROM todolist WHERE status='done' AND stamp < $old");
mysql_query($sql_deleteold);
I want to delete data from the database older than 30 days with the status "done".
Instead it will go deleting all rows with the status "done".

I think that your question is referring to the "second statement" in the SQL query?
With this assumption, the problem with all rows being deleted with the status "done" is because the WHERE filters are similar to conditional statements like the ones used in "If" statements.
If the first statement, or WHERE filter is true, then execute.
Try doing the following:
$old = time() - 2592000;
$sql_deleteold = ("DELETE FROM todolist WHERE (status='done' AND stamp < $old)");
mysql_query($sql_deleteold);
You also might want to verify the value of $old and compare it to the values in the 'stamp' field of your table, to be sure that there are some rows that have a value in the 'stamp' field that are greater than the value of $old.

Have you tried debugging your query? Rather than deleting the query try selecting the values:
SELECT * FROM todolist WHERE status = 'done' AND stamp < $old
Does it select the results you expect? If it doesn't keep tweaking it till it does, then attempt to delete the records.

You may have a quoting issue. To be sure, try:
$sql_deleteold = "DELETE FROM `todolist` WHERE `status`='done' AND `stamp` < '".$old."';";
Also when you insert fields, do you set the stamp field with php $time()$ function, or is it set by SQL functions? Because the time representation may be different depending on the type of the stamp field.

Try issuing SELECT stamp FROM todolist and see what you get. Presumably, they will be values less than time() = 2592000.

Related

MySQL Update query is not working with and operator

First query:
update tableA set columnA = 'Hello' and updated_at = now() where id = 10;
Second query:
update tableA set columnA = 'Hello', updated_at = now() where id = 10;
When I execute first query columnA updated as 0, where as second query worked fine and updated as Hello.
Why first query update the table as 0 value.
I think that MySQL's lax syntax is at work here. Consider rewriting your first update as:
UPDATE tableA
SET columnA = ('Hello' AND updated_at = NOW())
WHERE id = 10;
That is, the expression on the RHS being assigned to columnA is actually the AND of a string literal, and an assignment. Check the demo below to verify that this RHS in fact is evaluating to zero.
Demo
As to exactly why this is happening, we would have to lookup MySQL's rules for what happens. But best practice is to just stick with your second update query, which uses correct ANSI syntax.
#TimBiegeleisen is right, there is only one assigning expression for your first query.
MySQL syntax for SET assignment_list in UPDATE is like
assignment [, assignment] ...
every assigning expression for column separated by comma(,)
So, when you have multiple assignment use comma(,) to separate the assignment.
You found more details doc here

DLAST in Access

I am using DLAST to return a specific field value for the last record. The issue I am having is that the last record isn't always the newest date record. I need to return the value of a specific field for the newest date record.
You can't depend on DLast() to return a value from the "last record" of a table unless you use a query based on the table and indicate how the rows should be ordered. From the Application.DLast Method help topic ...
NoteIf you want to return the first or last record in a set of records (a domain), you should create a query sorted as either
ascending or descending and set the TopValues property to 1.
If you want to use DLast(), create a query and use the query name as the domain argument. For example, with this as Query1 ...
SELECT ASSY
FROM L2_AOI1
ORDER BY [your date field];
... this should work as the text box's Control Source ...
=DLast("ASSY", "Query1")
However, you could use a different query which returns the most recent ASSY and use DLookup with that query. For example, with Query2 ...
SELECT TOP 1 ASSY
FROM L2_AOI1
ORDER BY [your date field] DESC;
=DLookup("ASSY", "Query2")
Either way, include an index on [your date field] to optimize performance.
You can also use DLookup directly with an SQL clause:
=DLookup("Assy", "L2_AOI1", "[YourDateField] = (Select Max([YourDateField]) From L2_AOI1)")

Search for the Date "0000-00-00 00:00:00" in entire MySQL database?

I have a Huge database and somewhere in some table, there is a field with a datetime format that is corrupted with "0000-00-00 00:00:00" value.
How can I make a query, that will search for given datetime value ex. "0000-00-00 00:00:00" in entire database in all tables and all columns and rows?
With plain mysql I think there is no way. So it depends on the programming language you have available. Ofc. every language is supporting native commands of mysql, which would allow you to write a script performing the required search:
First, you need to fetch all tables:
SHOW TABLES
https://dev.mysql.com/doc/refman/5.0/en/show-tables.html
Then, in the first loop process every table, retrieving all the columns of the current table:
SHOW COLUMNS FROM tableName WHERE TYPE = 'date' -- Maybe you use other types?
https://dev.mysql.com/doc/refman/5.0/en/show-columns.html
Finally, you could use the outer value tableName along with the inner value columnName to retrieve the result, you are seeking for:
SELECT * from tableName WHERE columnName = '0000-00-00 00:00:00';
So, Script wise it might look like this (pseudocode):
$tables = query("SHOW TABLES");
foreach($tables as $tableName){
$columns = query("SHOW COLUMNS FROM $tableName WHERE TYPE = 'date'");
foreach ($columns AS $columnName) {
$res = query("SELECT * from $tableName WHERE $columnName = '0000-00-00 00:00:00';");
foreach ($res AS $row){
echo "Table $tableName has a invalid date in column $columnName for row {$row["id"]}";
}
}
}
You could try
SELECT TOP 1(*) FROM yourTable ORDER BY yourDateTimeColumn
The top 1 row should probably be the one with the value you're looking for
BTW, I thought SQL dates aren't earlier than 1900
You cannot do it in one simple query, but you can make a query that will construct a complicated one for you; I answered a similar question here.
In your case, you will probably need to have a DATA_TYPE = 'datetime' condition in the where, instead of the linked example's column_name condition.

Get previous record column value in SQL

I have a table that has 3 columns: date,name,salary
I want to query the table and add in the result set another calculated column that can have 2 values: 'new' and 'same'.
The rule to assign the value is: order records by date ascending. if the name of the current record is different from the name of the previous record then the new column value will be 'start' else (if it is the same) it will be 'same'.
How can i do that? is there a function (something like prevRow())? Or do i have to make a "trick"?
How can i do this in mysql and DB2?
It would seem that DB2 (versions after 9.7 at least) support the LAG() window function, so this query should work (although I haven't been able to test it):
SELECT
date,
name,
salary
CASE
WHEN lag(name, 1) OVER (ORDER BY date ASC) = name THEN 'same'
ELSE 'start'
END AS calc_col
FROM your_table
ORDER BY date ASC
Depends on the database you are using, MS SQL has a lag function : http://msdn.microsoft.com/en-us/library/hh231256.aspx
There is a mysql hack for this, check out this question : Simulate lag function in MySQL
how to do lag operation in mysql
You can use some query like this
set #last_val = "";
select
if(#last_val = column,"same","start") as state,
#last_val := colum as temp
from table
;

MySQL Selecting where datetime column =

Hi I am trying to get the following sql to work in mysql but it always return an empty result set - however there are definitely entries that match the criteria.
I'm new to mySQl so would appreciate if someone could point out where I am going wrong.
SELECT * FROM `ch_results`
WHERE 'readingDateTime' = '2011-03-29 20:00:00'
Remove the quotes around the field name:
SELECT *
FROM `ch_results`
WHERE readingDateTime = '2011-03-29 20:00:00'
Your current query compares string 'readingDateTime' to another string, '2011-03-29 20:00:00', which comparison of course never holds true.
Drop the quotes on the 'readingDateTime'. This is comparing strings to each other.
WHERE readingDateTime = '2011-03-29 20:00:00'