开发者

Selecting unique values from MySQL in a single query

I need to select all of the rows from the database where there is only ONE column that has a certain value. That is, if two rows have "ABC" as their value for column arbitrary then they are not returned.

I hope that's clear enough of wording to understand what I'm asking. Using MySQL's DISTINCT keyword is not feasible for what I need to do, as using it would require multiple queries. I'd like to be able to do this in one nice, compact query as it will be executed quite frequently. I'm in the process of scaling my application to allow a much higher degree of concurrency, and my current code just won't cut it anymore.

Currently, I'm using DISTINCT to select every unique value for the column in question, and then checking each of those values in another query to see if they only exist once. If so, keep it, if not, throw it away. Surely there is a mor开发者_如何学编程e prudent way to go about this?

Thanks.


SELECT * FROM table1 
GROUP BY the_column_that_must_be_unique
HAVING COUNT(*) = 1

To select only the values that are duplicate, and then only the most recent ones, so we can throw those out, lets call the the_column_that_must_be_unique u for short :-)

SELECT t1.* FROM table1 t1
INNER JOIN table1 t2 ON (t1.u = t2.u AND t1.id > t2.id)  

Note that I'm assuming id to by an auto-incrementing integer id, so that bigger id's means newer item. If that's not true than do

SELECT t1.* FROM table1 t1
INNER JOIN table1 t2 ON (t1.u = t2.u AND t1.id <> t2.id)
WHERE t1.atimestamp > t2.atimestamp  


SELECT col1,col2,....
FROM table_name
GROUP BY arbitrary
HAVING COUNT( arbitrary) =1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜