如何从mysql表中选择随机列?

时间:2017-09-20 12:45:28

标签: mysql database

我的桌子是这样的 -

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

我使用此查询 -

select * from table order by rand() limit 1

它只给我随机排。但我想随意选择任何主题,如下面的

Topic3
|mno| 

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

但条件是该列不应为空或为空。

2 个答案:

答案 0 :(得分:3)

请你检查这是否是你要求的?

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;

评论后更新版本并添加了子句-NULL /空白:

   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;

示例数据

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');

输出:

mysql version
1   5.7.12-log

TOPIC_RAND
1   cde
2   k4
3   i2

答案 1 :(得分:1)

规范化架构可能如下所示(代码段):

topic_id topic_name 
       1 abc  
       2 xyz  
       3 mno  
       4 pqr  

从这里开始,问题变得微不足道。