简体   繁体   中英

MySQL AND not working as expected

First of all, here is the query I am trying to use.

SELECT * FROM Messages t WHERE perspective_user=? and timestamp BETWEEN ? AND ? AND 
timestamp_added = 
(select max(timestamp_added) from Messages t2 
where 
t2.author = t.author AND
t2.body = t.body AND
t2.timestamp = t.timestamp AND
t2.timestamp_added <= ?
) AND convo_id IN (SELECT convo_id FROM Conversations WHERE perspective_user=? AND identity=? AND timestamp_added=?);

The code works fine without the following line, but with it, it returns 0 results.

AND convo_id IN (SELECT convo_id FROM Conversations WHERE perspective_user=? AND identity=? AND timestamp_added=?);

I've also verified that the above line works on its own, tested on a basic SELECT * query. I've also made sure that there are rows in the database that satisfy the top query.

The data is a log of Skype messages. Logs are taken randomly; the goal is to get the most recent log that is still in the database. The goal is to be able to graph my Skype messages and do other fun things. Skype purges its database on my computer of older messages. The long "timestamp_added" statement is to get the newest of each message, so that if the latest log had a purged database, old messages would still be included.

First thing, that I see is that you have a space between IN and parenthesis — MySQL "hates" it. Fix it like that:

...AND convo_id IN(SELECT... 

But if it's just topic posting typo error, then please share your data (MySQL scheme of Messages and Conversations ).

The statement below return a list of rows where as what you need to pass to an IN() function is a CSV.

(SELECT convo_id FROM Conversations WHERE perspective_user=? AND identity=? AND timestamp_added=?)

So instead use GROUP_CONCAT() like this

(SELECT GROUP_CONCAT(convo_id) FROM Conversations WHERE perspective_user=? AND identity=? AND timestamp_added=? GROUP BY convo_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM