im try to execute sql query that will check if some time (like 10 sec) past from last timestamp update in my table and chenge other table if yes.
My question is if ther is any time-stamp conditional operator that can check this? For example
< , > ,=?
(I know that I can do it in to different query, but I'm try do to it in 1 query)..
Something like this
UPDATE Person SET isconnected=false
where person.email=(select from imalive where timestamp<10).
person:
email: dan#gmail.com
name: dan
age: 20
isAlive:
email: dan#gmail.com
lastseen: 2011-09-04 21:27:00
So at last if the person is last seen will be more then 10 sec he will go to isconnected =false.
Syntax would change slightly per database. Here's an example for SQL Server using not exists:
update Person
set IsConnected = 0
where IsConnected <> 0
and not exists
(
select *
from IsAlive
where Person.email = IsAlive.email
and IsAlive.timestamp > dateadd(s,-10,getdate())
)
Related
I unsuccessfully attempted to leverage Java's DerivedQueries but cannot accomplish the required result so I have to manually write a SELECT Statement.
I want to display one single record in my UI. This should be the most recently generated record (which means it has the highest ID Number) associated with a category that we call "ASMS". In other words, look through all the rows that have ASMS#123, find the one that has the highest ID and then return the contents of one column cell.
ASMS: Entries are classified by 11 specific ASMS numbers.
ID: AutoGenerated
PPRECORD: New entries being inserted each day
I hope the image makes more sense.
//RETURN ONLY THE LATEST RECORD
//https://besterdev-api.apps.pcfepg3mi.gm.com/api/v1/pprecords/latest/{asmsnumber}
#RequestMapping("/pprecords/latest/{asmsNumber}")
public List<Optional<PriorityProgressEntity>> getLatestRecord(#PathVariable(value = "asmsNumber") String asmsNumber) {
List<Optional<PriorityProgressEntity>> asms_number = priorityprogressrepo.findFirst1ByAsmsNumber(asmsNumber);
return asms_number;}
The ReactJS FE makes an AXIOS.get and I can retrieve all the records associated with the ASMS, but I do not have the skill to display only JSON object that has the highest ID value. I'm happy to do this in the FE also.
I tried Derived Queries. .findFirst1ByAsmsNumber(asmsNumber) does not consider the highest ID number.
Try this:
SELECT pprecord FROM YourTable WHERE id =
(SELECT MAX(id) FROM YourTable WHERE asms = '188660')
Explanation:
First line select pprecord, second line select the id
I'll improve the answer if any additional question. Upvotes and acceptions are appreciated~
I have a SQLite table content with following columns:
-----------------------------------------------
|id|book_name|chapter_nr|verse_nr|word_nr|word|
-----------------------------------------------
the sql query
select count(*) from content where book_name = 'John'
group by book_name, chapter_nr
in DB Browser returns 21 rows (which is the count of chapters)
the equivalent with ORMLite android:
long count = getHelper().getWordDao().queryBuilder()
.groupByRaw("book_name, chapter_nr")
.where()
.eq("book_name", book_name)
.countOf();
returns 828 rows (which is the count of verse numbers)
as far as I know the above code is translated to:
select count(*) from content
where book_name = 'John'
group by book_name, chapter_nr
result of this in DB Browser:
| count(*)
------------
1 | 828
2 | 430
3 | 653
...
21| 542
---------
21 Rows returned from: select count(*)...
so it seems to me that ORMLite returns the first row of the query as the result of countOf().
I've searched stackoverflow and google a lot. I found this question (and more interestingly the answer)
You can also count the number of rows in a custom query by calling the > countOf() method on the Where or QueryBuilder object.
// count the number of lines in this custom query
int numRows = dao.queryBuilder().where().eq("name", "Joe Smith").countOf();
this is (correct me if I'm wrong) exactly what I'm doing, but somehow I just get the wrong number of rows.
So... either I'm doing something wrong here or countOf() is not working the way it is supposed to.
Note: It's the same with groupBy instead of groupByRaw (according to ORMLite documentation joining groupBy's should work)
...
.groupBy("book_name")
.groupBy("chapter_nr")
.where(...)
.countOf()
EDIT: getWordDao returns from class Word:
#DatabaseTable(tableName = "content")
public class Word { ... }
returns 828 rows (which is the count of verse numbers)
This seems to be a limitation of the QueryBuilder.countOf() mechanism. It is expecting a single value and does not understand the addition of GROUP BY to the count query. You can tell that it doesn't because that method returns a single long.
If you want to extract the counts for each of the groups it looks like you will need to do a raw query check out the docs.
Ok, so I am a little new to MySQL querys and I am wondering if this would be the correct syntax to get if a value is false in a row.
"SELECT `status`
FROM `friends`
WHERE `requester`= '"+requester+"'
AND `requested` = '"+requested+"'
AND `status`= 'false'";
If that is wrong, I'm trying to fetch the requests where you are the requester and the status is false through a java method.
first thing i would do is check to be sure the variables contain what you want them to. maybe even put in the data directly to the query at first without variables. get it to what you want it to be.
System.out.println("the requester is: ");
System.out.println(requester);
System.out.println("the requested is: ");
System.out.println(requested);
"SELECT 0 FROM friends WHERE requester= '"+requester+"' AND requested = '"+requested+"' AND status= 'false'"
generally 0 is false and 1 is true in programming languages so you can just pull out a 0 when its false.
you may want to also do a like comparison on the requester and requested. you could do it on the status column if you want but that shouldn't be necessary
"SELECT 0 FROM friends WHERE requester LIKE '%"+requester+"%' AND requested LIKE '%"+requested+"%' AND status= 'false'"
Your query want work only if there is some white space char in your value else your query is fine to check try this use like
SELECT status FROM friends WHERE requester= '"+requester+"' AND requested = '"+requested+"' AND status like '%false';
try this man
status is false
in your case, false is a string, not a boolean
I'm having some trouble here to create an appropriate SQL query. Any help will be much appreciated!
Some background:
I have the following entities
Equipment
id
nickname
owner_indicator
{...}
EquipmentGroup_Equipment
equipment_id
equipment_group_id
EquipmentGroup
id
name
description
I need to do a SQL / JPA Hibernate query that returns me:
EquipmentGroup.name, EquipmentGroup.description, Equipment.owner_indicator
And this will be grouped by EquipmentGroup.id, so if I have 10 equipments inside the group it will return information grouped by the EquipmentGroup.
The thing is, when I have for example more than one owner_indicator inside a EquipmentGroup it will return 2 rows. This is SQL 101. But i must return only one line with a blank text instead of the Owner Indicator.
What is the easiest way to do this ? I'd be glad to have the answer in SQL, but much more than glad to have it in Criteria JPA, heh.
If it does matter, I'm using Oracle 12c.
Thanks!
EDIT
As requested, here is some data:
Equipment
id nickname owner_indicator
1 EQP01 'V'
2 EQP02 'T'
EquipmentGroup_Equipment
equipment_group_id equipment_id
1 1
1 2
EquipmentGroup
id name description
1 GRP1 Group 1
My wanted resultSet is:
Result
EquipmentGroup.name EquipmentGroup.description, Equipment.owner_indicator
GRP1 Group 1 (empty string)
That empty string would be returned because I don't want 2 rows, like
Result
EquipmentGroup.name EquipmentGroup.description, Equipment.owner_indicator
GRP1 Group 1 'T'
GRP1 Group 1 'V'
If anything more than that is needed please advise.
Thanks!
I thin k you must to use a main query on EquipmentGroup and a subquery about return data on Equipment.
If you have more than 1 equipment rows about one group you must return DISTINCT empty; if you have 1 row returns owner_indicator otherwise you can return 'None'
Try this:
SELECT DISTINCT eg.name, eg.description,
(SELECT
CASE
WHEN count(e.id) > 1 THEN DISTINCT 'EMPTY'
WHEN count(e.id) = 1 THEN e.owner_indicator
ELSE 'none'
END
FROM Equipment e
WHERE e.equipmentGroup.id = eg.id)
FROM EquipmentGroup eg
I have this SQL query which queries the database every 5 seconds to determine who is currently actively using the software. Active users have pinged the server in the last 10 seconds. (The table gets updated correctly on user activity and a I have a thread evicting entries on session timeouts, that all works correctly).
What I'm looking for is a more efficient/quicker way to do this, since it gets called frequently, about every 5 seconds. In addition, there may be up to 500 users in the database. The language is Java, but the question really pertains to any language.
List<String> r = new ArrayList<String>();
Calendar c = Calendar.getInstance();
long threshold = c.get(Calendar.SECOND) + c.get(Calendar.MINUTE)*60 + c.get(Calendar.HOUR_OF_DAY)*60*60 - 10;
String tmpSql = "SELECT user_name, EXTRACT(HOUR FROM last_access_ts) as hour, EXTRACT(MINUTE FROM last_access_ts) as minute, EXTRACT(SECOND FROM last_access_ts) as second FROM user_sessions";
DBResult rs = DB.select(tmpSql);
for (int i=0; i<rs.size(); i++)
{
Map<String, Object> result = rs.get(i);
long hour = (Long)result.get("hour");
long minute = (Long)result.get("minute");
long second = (Long)result.get("second");
if (hour*60*60 + minute*60 + second > threshold)
r.add(result.get("user_name").toString());
}
return r;
If you want this to run faster, then create an index on user_sessions(last_access_ts, user_name), and do the date logic in the query:
select user_name
from user_sessions
where last_access_ts >= now() - 5/(24*60*60);
This does have a downside. You are, presumably, updating the last_access_ts field quite often. An index on the field will also have to be updated. On the positive side, this is a covering index, so the index itself can satisfy the query without resorting to the original data pages.
I would move the logic from Java to DB. This mean you translate if into where, and just select the name of valid result.
SELECT user_name FROM user_sessions WHERE last_access_ts > ?
In your example the c represent current time. It is highly possible that result will be empty.
So your question should be more about date time operation on your database.
Just let the database do the comparison for you by using this query:
SELECT
user_name
FROM user_sessions
where TIMESTAMPDIFF(SECOND, last_access_ts, current_timestamp) > 10
Complete example:
List<String> r = new ArrayList<String>();
Calendar c = Calendar.getInstance();
long threshold = c.get(Calendar.SECOND) + c.get(Calendar.MINUTE)*60 + c.get(Calendar.HOUR_OF_DAY)*60*60 - 10;
// this will return all users that were inactive for longer than 10 seconds
String tmpSql = "SELECT
user_name
FROM user_sessions
where TIMESTAMPDIFF(SECOND, last_access_ts, current_timestamp) > 10";
DBResult rs = DB.select(tmpSql);
for (int i=0; i<rs.size(); i++)
{
Map<String, Object> result = rs.get(i);
r.add(result.get("user_name").toString());
}
return r;
SQLFiddle
The solution is to remove the logic from your code to the sql query to only get the active users from that select, using a where clause.
It is faster to use the sql built-in functions to get fewer records and iterate less in your code.
Add this to your sql query to get the active users only:
Where TIMESTAMPDIFF(SECOND, last_access_ts, current_timestamp) > 10
This will get you all the records whose date is 10 seconds ago or sooner.
Try the MySQL TimeDiff function in your select. This way you can select only the results that are active without having to do any other calculations.
Link: MySQL: how to get the difference between two timestamps in seconds
If I get you right, then you got only 500 entries in your user_sessions table. In this case I wouldn't even care about indexes. Throw them away. The DB engine probably won't use them anyway for such a low record count. The performance gain due to not updating the indexes on every record update could be probably higher than the query overhead.
If you care about DB stress, then lengthen the query/update intervals to 1 minute or more, if your application allows this. Gordon Linoff's answer should give you the best query performance though.
As a side note (because it has bitten me before): If you don't use the same synchronized time for all user callbacks, then your "active users logic" is flawed by design.