为 SQL 连接选择单个(随机)行
我有一个从多个表中选择数据的 sql 查询,但我只想匹配另一个表中的单个(随机选择)行。
我想更容易显示一些代码;)
表 K 是 (k_id, selected) 表C是(c_id, image) 表S是(c_id,日期) 表 M 为 (c_id, k_id, Score)
所有 ID 列都是主键,具有适当的 FK 约束。
用英语来说,我想要的是 K 中选择 = 1 的每一行从 C 中获取随机行,其中 M 中存在带有 (K_id, C_id) 的行,其中分数高于给定值,并且其中 c.image 不为空,并且 s 中有一行带有 c_id
类似:
select k.k_id, c.c_id, m.score
from k,c,m,s
where k.selected = 1
and m.score > some_value
and m.k_id = k.k_id
and m.c_id = c.c_id
and c.image is not null
and s.c_id = c.c_id;
唯一的问题是这会返回 C 中符合条件的所有行 - 我只想要一个...
我可以看到如何使用PL/SQL 将所有相关行选择到集合中,然后选择随机行,但我不知道如何选择随机行。
I've got an sql query that selects data from several tables, but I only want to match a single(randomly selected) row from another table.
Easier to show some code, I guess ;)
Table K is (k_id, selected)
Table C is (c_id, image)
Table S is (c_id, date)
Table M is (c_id, k_id, score)
All ID-columns are primary keys, with appropriate FK constraints.
What I want, in english, is for eack row in K that has selected = 1 to get a random row from C where there exists a row in M with (K_id, C_id), where the score is higher than a given value, and where c.image is not null and there is a row in s with c_id
Something like:
select k.k_id, c.c_id, m.score
from k,c,m,s
where k.selected = 1
and m.score > some_value
and m.k_id = k.k_id
and m.c_id = c.c_id
and c.image is not null
and s.c_id = c.c_id;
The only problem is this returns all the rows in C that match the criteria - I only want one...
I can see how to do it using PL/SQL to select all relevent rows into a collection and then select a random one, but I'm stuck as to how to select a random one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在查询中使用“order by dbms_random.random”指令。
即:
参考文献:
http://awads.net/wp/2005/08 /09/无序排序/
http://www.petefreitag.com/item/466.cfm
you can use the 'order by dbms_random.random' instruction with your query.
i.e.:
References:
http://awads.net/wp/2005/08/09/order-by-no-order/
http://www.petefreitag.com/item/466.cfm
with Analytics:
这将选择满足每个 k_id 标准的一行。如果您多次运行查询,这可能会选择同一组行。如果您想要更多随机性(每次运行生成不同的行集),您可以将
ORDER BY NULL
替换为ORDER BY dbms_random.value
with analytics:
This will select one row that satisfies your criteria per k_id. This will likely select the same set of rows if you run the query several times. If you want more randomness (each run produces a different set of rows), you would replace
ORDER BY NULL
byORDER BY dbms_random.value
我对oracle SQL不太熟悉,但是如果有这样的函数可用,请尝试使用LIMIT random()。
I'm not too familiar with oracle SQL, but try using LIMIT random(), if there is such a function available.