简体   繁体   中英

Double MySQL query

I'm currently developing an app with a vote feature. I would like people not to sign in and make it simple, so I collect the IP after every vote. With this feature the IP will never vote on the same thing again.

But I find it hard to SELECT a voting, that hasn't been voting by the IP. I've tried this:

SELECT * FROM messages 
WHERE state = '-1' 
  AND id != (SELECT message_id FROM log WHERE ip = '$ip')

How do I do this correctly?

If I understood you correctly - this query should help you:

SELECT messages.* FROM messages 
LEFT JOIN log ON log.message_id = messages.id AND log.ip = '$ip'
WHERE state = '-1' AND log.ip IS NULL
SELECT * FROM messages 
WHERE state = '-1' 
  AND id NOT IN (SELECT message_id FROM log WHERE ip = '$ip')

will do what you say, but I am quite positive it will not do what you want: Eg it will allow only one mobile user of a typical cell tower to vote, but will allow him to vote again, after he has lost signal and regathered it at an other location.

$qry = "SELECT * FROM messages " .
"WHERE state = '-1' AND NOT EXISTS (SELECT 1 FROM log WHERE log.message_id = messages.id  ". 
"AND ip = '" . $ip . "')";

A (NOT) EXISTS is usually faster than a IN expression

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