Sunil Kothiyal
Sunil Kothiyal

Reputation: 177

How select random column from mysql table?

My table is like this -

+---------+---------------+------+-----+---------+-------+
| PK      | ToicID        |topic1|topic2| topic3 |topic4 |
+---------+---------------+------+-----+---------+-------+
| 1       | 1             | abc  | xyz  | mno    | pqr   |
+---------+---------------+------+-----+---------+-------+

I use this query-

select * from table order by rand() limit 1

it's giving me only random row. But I want to select any topic random like following

Topic3
|mno| 

==========================================

But conditon is that column should't empty or null.

Upvotes: 1

Views: 520

Answers (2)

Strawberry
Strawberry

Reputation: 33945

A normalized schema might look like this (snippet):

topic_id topic_name 
       1 abc  
       2 xyz  
       3 mno  
       4 pqr  

From here, the problem becomes trivial.

Upvotes: 1

etsa
etsa

Reputation: 5060

Pls can you check if this is what you are asking for?

SELECT  CASE FLOOR(RAND()*4+1)
             WHEN 1 THEN TOPIC1 
             WHEN 2 THEN TOPIC2 
             WHEN 3 THEN TOPIC3 
             WHEN 4 THEN TOPIC4 END AS TOPIC_RAND
FROM TABLE;

Updated version after comments and added clause -NULL/blank in question:

   select version() as 'mysql version';

SELECT  CASE FLOOR(RAND()*4+1)   /*wrote here just 1 to make tests */
    WHEN 1 THEN COALESCE(TOPIC1, TOPIC2, TOPIC3, TOPIC4)  
    WHEN 2 THEN COALESCE(TOPIC2, TOPIC3, TOPIC4, TOPIC1) 
    WHEN 3 THEN COALESCE(TOPIC3, TOPIC4, TOPIC1, TOPIC2) 
    WHEN 4 THEN COALESCE(TOPIC4, TOPIC1, TOPIC2, TOPIC3) END AS TOPIC_RAND
FROM (SELECT NULLIF(TOPIC1,'') AS TOPIC1, NULLIF(TOPIC2,'') AS TOPIC2,NULLIF(TOPIC3,'') AS TOPIC3,NULLIF(TOPIC4,'') AS TOPIC4          
      FROM TTE1) A;

Sample data

CREATE TABLE TTE1 (TOPIC1 VARCHAR(10), TOPIC2 VARCHAR(10), TOPIC3 VARCHAR(10), TOPIC4 VARCHAR(10));
INSERT INTO TTE1 VALUES ('abc','cde','efg','hij');
INSERT INTO TTE1 VALUES (NULL,'k2','k3','k4');
INSERT INTO TTE1 VALUES ('','i2','i3','i4');

Output:

mysql version
1   5.7.12-log

TOPIC_RAND
1   cde
2   k4
3   i2

Upvotes: 3

Related Questions