从重复记录中选择顶级唯一记录,然后随机播放并显示其余的重复记录

时间:2015-03-09 07:31:06

标签: php mysql

我要求首先显示重复值中的top first_name唯一记录,然后将其余数据随机播放。 我的桌子是这样的:

id  com_id  company_name    company_id
1   1          mufti            1
2   1          mufti            1
3   1          mufti            1
4   2          fcuk             2
5   2          fcuk             2
6   2          fcuk             2
7   3          denim            3
8   3          denim            3
9   3          denim            3

我尝试了下面提到的查询,我能够获取第一个顶级唯一记录,但是rand的顺序没有显示随机数据,或者是否有任何可能的方法使用其他rand()来重新打印其余记录。< / p>

SELECT * 
FROM product_data AS td 
WHERE NOT EXISTS ( SELECT * 
                   FROM product_data AS t 
                   WHERE t.company_id=td.company_id 
                     AND t.id=td.id- 1 )  
UNION ALL 
SELECT * 
FROM `product_data` 
WHERE `id` NOT IN (SELECT id 
                   FROM product_data AS td 
                   WHERE NOT EXISTS ( SELECT `id` 
                                      FROM product_data AS t 
                                      WHERE t.company_id=td.company_id
                                      AND t.id=td.id- 1 ) 
                   ORDER BY id,RAND())

输出:

id  com_id  company_name    company_id
1   1            mufti         1
4   2            fcuk          2
7   3            denim         3
2   1            mufti         1
3   1            mufti         1
5   2            fcuk          2
6   2            fcuk          2
8   3            denim         3
9   3            denim         3

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

SET @row_number = 0;
SELECT id, com_id, company_name, company_id, rand
FROM ( SELECT *, (@row_number := @row_number + 1) AS rand
FROM product_data AS td
WHERE NOT EXISTS ( SELECT * 
                   FROM product_data AS t 
                   WHERE t.company_id=td.company_id 
                     AND t.id=td.id- 1 ) 
UNION ALL
SELECT *, ROUND(RAND() * 10, 2) + 3 AS rand
FROM product_data
WHERE id NOT IN (SELECT id 
                   FROM product_data AS td 
                   WHERE NOT EXISTS ( SELECT id
                                      FROM product_data AS t 
                                      WHERE t.company_id=td.company_id
                                      AND t.id = td.id - 1 ) 
                                    )
ORDER BY rand ) AS temp

我添加了一个rand列,它是必须位于第一个位置的唯一元素的渐进数字,以及其他元素的随机数。