简体   繁体   English

如何使用随机列MYSQL选择Distinct?

[英]How to select Distinct with random column MYSQL?

I've table books that contains image, language, faith. 我有一些包含图像,语言,信仰的桌子books I'am getting distinct values for faith with 我正在与众不同的信念价值观

SELECT DISTINCT faith, language from books;

That fetches faith series ( 15 results ) but I want to fetch image along too but randomly. 这获取了信仰系列( 15个结果 ),但我也想随机获取image So the result can be able to show faith with random image. 因此,结果可以显示随机图像的可信度。 How I can do that, please suggest. 我该怎么做,请提出建议。

The query 查询

select distinct faith, language from books;

selects distinct Faith-Language combinations from your table. 从表中选择不同的信仰-语言组合。 So where your table contains two entries for the same Faith and Language 因此,您的表中包含相同信仰和语言的两个条目

Faith  Language  Image
1      EN        img1
1      EN        img2
1      FR        img3
1      FR        img4

your result would contain each combination just once: 您的结果将仅包含每个组合一次:

Faith  Language
1      EN
1      FR

It is not clear from your question yet, what you mean with a random image. 从您的问题还不清楚,您对随机图像的含义是什么。 Here is how you get one of the matching images for a Faith-Language combination arbitrarily picked: 这是如何获取任意选择的信念语言组合的匹配图像之一的方法:

select faith, language, image
from books
group by faith, language;

The result could look like this: 结果可能如下所示:

Faith  Language  Image
1      EN        img2
1      FR        img3

The reason is that we aggregate the rows. 原因是我们汇总了行。 In the GROUP BY clause we say we want one result row per Faith and Language, but we also select Image and don't specify which one we'd like to see per group (which we could do with an aggregate function like MIN or MAX), so we just get one of the images matching the Faith-Language combination arbitrarily picked by the DBMS. 在GROUP BY子句中,我们说我们希望每个信念和语言一行,但我们也选择了Image,并且没有指定我们希望每个组看到哪个行(我们可以使用MIN或MAX这样的聚合函数来完成该行),因此我们只获得与DBMS任意选择的与信念语言组合相匹配的图像之一。

Is this already what you want? 这已经是您想要的吗?

Thank to everybody, i got the solution from 谢谢大家,我得到了解决方案

Select random row per distinct field value? 为每个不同的字段值选择随机行?

SELECT r.faith, 
(SELECT r1.image FROM books AS r1 WHERE r.faith=r1.faith ORDER BY rand() LIMIT 1) AS image FROM books AS r GROUP BY r.faith;  

it's fetching distinct field1 faith with random field2 image against each faith everytime query executed. 每次执行查询时,它都会针对每个信念获取具有随机field2图像的不同field1 faith

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM