0

我有这个表,它可以很容易地按 id asc 或 desc 排序,但它总是会给出相同的结果,所以只有通过 asc 或 desc 获得两个结果的可能性这里是 tablea

                    id              linkid      

                    5454             766
                    5453             766
                    5452             766
                    5451             766
                    5450             766
                    5449             766
                    5448             765
                    5447             765
                    5446             765
                    5445             765
   select * from tablea where linkid='766' order by id desc limit 1

   or
                select * from tablea where linkid='766' order by id asc limit 1                            

当我使用上面的查询时,我只有两个选项可以使用 asc 或 desc,它们只能以两种方式对 linkid 766 进行排序,我将获得 id 5454 或 5449 的输出,但我想使用与 linkid 相对应的任何一个 id。我想要这样的linkid 766的输出。查询应该给出任何一个值,不仅是我通过使用asc或desc获得的第一个或最后一个值,而且我不想使用rand(),因为它非常慢

我可以尝试 rand() 但它会很慢

     select * from tablea where linkid='766' order by rand()  limit 1    

任何想法如何实现。

4

2 回答 2

0

If your expected result set from the query is small enough, then you may want to consider using app tier for randomizing your selection. I do not know your database infrastructure or load but general rule of thumb I use is that "App Tier is far more easier to scale then the database tier"!

Having said that, I know there are some situations where you really want to randomize results at the DB tier. We had to do that in couple of instances and in our research, we stumbled upon following which seems to have worked for us. http://www.rndblog.com/how-to-select-random-rows-in-mysql/

It doesn't make sense to repeat everything here, but for the sake of ensuring that if the page at the given link disappears, here is a high level summary. Basically, what this link is discussing is.... instead of using RAND in the order by clause (which can be very expensive)

SELECT col1 FROM tbl ORDER BY RAND() LIMIT 10;

Use it in the WHERE clause:

SELECT col1 FROM tbl WHERE RAND()<=0.0006 limit 100;

Hope this helps you.

于 2013-05-07T00:41:04.790 回答
0

你试过这个吗?

SELECT * FROM table LIMIT 1 ORDER BY id DESC

或者

SELECT * FROM table ORDER BY id DESC
于 2016-08-11T08:52:54.577 回答