I've table books
that contains image, language, faith. 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. 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.
Is this already what you want?
Thank to everybody, i got the solution from
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.