I want to create an SQL statement (using sqllite.. so I can’t use functions, IF statements etc..) that reuses the result of a select statement.. this is what it currently looks like
INSERT INTO search_email(many_fields, threadid) VALUES ('many_fields',
CASE
WHEN
(
(SELECT COUNT(tableX.threadid) %threadIDquery%
) > 0
)
THEN
(SELECT tableX.threadid %threadIDquery% LIMIT 1)
ELSE
0
END
)
I want to reuse the result of first select instead of having to make another (almost identical) select statement.
update: for those wondering what i’m trying to do.. here is the full version of the query:
INSERT INTO search_email(meta, subject, body, sender, tos, ccs, folder, threadid) VALUES ('meta1','subject1','body1','sender1', 'tos1',' ccs1','folder1',
CASE
WHEN
(
(SELECT COUNT(search_email.threadID) FROM search_email
WHERE search_email.subject MATCH '%query%' AND
(
(search_email.sender = '%sender' AND search_email.tos = '%receiver%')
OR
(search_email.sender = '%receiver%' AND search_email.tos = '%sender%')
)
) > 0
)
THEN
(SELECT search_email.threadID FROM search_email
WHERE search_email.subject MATCH '%query%' AND
(
(search_email.sender = '%sender%' AND search_email.tos = '%receiver%')
OR
(search_email.sender = '%receiver%' AND search_email.tos = '%sender%')
) LIMIT 1
)
ELSE
//generate new thread ID
END
)
basically i’m trying to find out if an email thread already exists for an incoming email.. so i check if the subject matches and if it does, i check to see if the sender and receiver of the email match (in either direction).. if the email thread exists i just insert the same email threadID, else i generate a new threadID
update 2:just to clarify, I’m looking for a way to save the sqllite compiler from making the same search twice.. rather than simply saving on typing (or making it more readable etc)
update 3: i was wondering if there was a way for this statement to return the generated threadID iff the threadID was retrieved from the dbase, rather than generated.. you can find the answer here
This is an alternative way of structuring the query:
This is using a
selectinstead ofvalues. It gets the thread id that matches the conditions, or NULL if none match. The second clause of thecoalesceis then run when the first is NULL. You can generate the new id there.I do have a problem with this approach. To me, it seems that you should have a Thread table that manages the threads. The ThreadId should be an autoincremented id in this table. The emails table can then reference this id. In other words, I think the data model needs to be thought out in more detail.
The following query will not query work, but it gives the idea of moving the thread to the subquery:
The reason it will not work is because the
fromclause will return no rows rather than 1 row with a NULL value. So, to get what you want, you can use:This ensures that a NULL value is returned when there is no thread.