[英]SQL: select random row from table where the ID of the row isn't in another table?
I've been looking at fast ways to select a random row from a table and have found the following site: http://74.125.77.132/search?q=cache:http://jan.kneschke.de/projects/mysql/order-by-rand/&hl=en&strip=1 我一直在寻找从表中选择随机行的快速方法,并找到以下站点:http: //74.125.77.132/search?q=cache :http: //jan.kneschke.de/projects/mysql / order-by-rand /&hl = zh-CN&strip = 1
What I want to do is to select a random url from my table 'urls' that I DON'T have in my other table 'urlinfo'.The query I am using now selects a random url from 'urls' but I need it modified to only return a random url that is NOT in the 'urlinfo' table. 我想做的是从我的其他表'urlinfo'中没有的表'urls'中选择一个随机URL。我正在使用的查询现在从'urls'中选择一个随机URL,但我需要对其进行修改只返回不在“ urlinfo”表中的随机网址。
Heres the query: 这是查询:
SELECT url
FROM urls JOIN (SELECT CEIL(RAND() * (SELECT MAX(urlid)
FROM urls
)
) AS urlid
) AS r2 USING(urlid);
And the two tables: 和两个表:
CREATE TABLE urls (
urlid INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
url VARCHAR(255) NOT NULL
) ENGINE=INNODB;
CREATE TABLE urlinfo (
urlid INT NOT NULL PRIMARY KEY,
urlinfo VARCHAR(10000),
FOREIGN KEY (urlid) REFERENCES urls (urlid)
) ENGINE=INNODB;
How about working from this random solution: 如何使用此随机解决方案:
SELECT TOP 1 * FROM urls
WHERE (SELECT COUNT(*) FROM urlinfo WHERE urlid = urls.urlid) = 0
ORDER BY NEWID()
You need to first do a left outer join to get the set of records in 'urls' that are not in 'urlinfo', then pick a random record from that set. 您需要首先执行左外部联接,以获取不在“ urlinfo”中的“ url”中的记录集,然后从该记录集中选择一个随机记录。
SELECT * FROM urls
LEFT OUTER JOIN urlinfo
ON urls.urlid = urlinfo.urlid
WHERE urlinfo.urlid IS null
Now pick a random row from this set - you can do something like 现在从该集合中随机选择一行-您可以执行类似
SELECT newUrls.url
FROM (
SELECT urls.urlid, urls.url FROM urls
LEFT OUTER JOIN urlinfo
ON urls.urlid = urlinfo.urlid
WHERE urlinfo.urlid IS null
) as newUrls
WHERE urls.urlid >= RAND() * (SELECT MAX(urlid) FROM urls) LIMIT 1
However, this will only work if the urlids in urlinfo are roughly randomly distributed across the range of possible values. 但是,只有在urlinfo中的urlid大致随机分布在可能值的范围内时,这才起作用。
You could use where not exists
to exclude rows that are in the other table. 您可以使用
where not exists
来排除另一个表中的行。 For a random row, one option is a order by rand()
with a limit 1
: 对于随机行,一个选项是
order by rand()
的limit 1
的order by rand()
:
SELECT url
FROM urls
WHERE NOT EXISTS (
SELECT *
FROM urlinfo ui
WHERE ui.urlid = urls.urlid
)
ORDER BY RAND()
LIMIT 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.