4列的DISTINCT值

时间:2013-12-13 06:59:25

标签: mysql sql codeigniter activerecord

我有一张这样的表:

maiL_client   platform   rendering_engine   category

Android         mobile     Webkit           read
Android         mobile     Webkit           deleted
Apple iPhone    mobile     Webkit           skimmed
Other           Other      desktop          read
Other           Other      desktop          deleted
Android         Other      mobile           skimmed

现在我需要的是获取所有这些列的不同值。是否可以在一个查询中获取它?如果我使用简单的SELECT DISTINCT column_names,那么它将生成重复值。我在CodeIgniter活动记录模式中使用它。

5 个答案:

答案 0 :(得分:2)

SELECT DISTINCT 'mail_client' AS `key`,mail_client as `value` FROM table
UNION
SELECT DISTINCT 'platform', platform FROM table
UNION
SELECT DISTINCT'rendering_engine', rendering_engine FROM table
UNION
SELECT DISTINCT'category', category FROM table

或尝试以下内容,然后拆分或分解结果,因为它将返回以逗号分隔的列表

SELECT GROUP_CONCAT(DISTINCT Mail_Client)as Mail_client,
       GROUP_CONCAT(DISTINCT platform) as platform,
       GROUP_CONCAT(DISTINCT rendering_engine)as rendering_engine,
       GROUP_CONCAT(DISTINCT category)as category
FROM Table

sqlFiddle Demo

结果

MAIL_CLIENT                 PLATFORM      RENDERING_ENGINE      CATEGORY
-----------                 ---------     ----------------      --------
Android,Apple iPhone,Other  mobile,Other  Webkit,desktop,mobile read,deleted,skimmed

答案 1 :(得分:0)

试试这个,这可以帮到你:

    SELECT maiL_client FROM `<tablename>` GROUP BY maiL_client
    union 
    SELECT plateform  FROM `<tablename>` GROUP BY plateform
    union
    SELECT rendering_engine  FROM `<tablename>` GROUP BY rendering_engine
    union
    SELECT category  FROM `<tablename>` GROUP BY category

答案 2 :(得分:0)

你可以这样试试。不知道是否在MySQL中工作。

SELECT DISTINCT TMP1.maiL_client, TMP2.platform, TMP3.rendering_engine, TMP4.category
FROM
( SELECT DISTINCT maiL_client  FROM TABLE_NAME) AS TMP1,
( SELECT DISTINCT platform FROM TABLE_NAME) AS TMP2,  
( SELECT DISTINCT rendering_engine FROM TABLE_NAME) AS TMP3,  
( SELECT DISTINCT category FROM TABLE_NAME) AS TMP4

答案 3 :(得分:0)

你可以尝试这个...我不习惯sql语法..但希望你得到我的逻辑..

select A,B,C,D from
(select disitnct A,rownumber() as row_num from Table) as a outer join on a.row_num =b.row_num
(select disitnct B,rownumber() as row_num from Table) as b outer join on b.row_num =c.row_num
(select disitnct C,rownumber() as row_num from Table) as c outer join on c.row_num =d.row_num
(select disitnct D,rownumber() as row_num from Table) as d outer join on d.row_num =a.row_num

答案 4 :(得分:-5)

SELECT DISTINCT maiL_client, platform, rendering_engine, category FROM <YourTable>