Archive: Posts Tagged ‘SQL’

SQL: UNION ALL / rand() / using

No comments April 23rd, 2010

1. 随机取3条记录,不连续:
select * from tbA JOIN (SELECT ceil(rand() * (select max(id) from tbA)) as ID) as r2 using (id) UNION ALL
select * from tbA JOIN (SELECT ceil(rand() * (select max(id) from tbA)) as ID) as r2 using (id) UNION ALL
select * from tbA JOIN (SELECT ceil(rand() * (select max(id) from tbA)) as ID) as r2 using (id) ;
这里的using(id)是什么意思?

2. 得到随机的3条连续记录:
select * from tbA as a join (select round(rand()* ((select max(id) from tbA where type=1)-(select min(id) from resume_message where type=1))+(select min(id) from resume_message where type=1)) as nid) as b where a.id>=b.nid and type=1 limit 3;

Some useful SQLs

1 comment April 20th, 2010

1. SHOW CREATE TABLE tbA;

2. UPDATE tbA JOIN tbB ON tbA.`id`=tbB.a`id` SET tbA.`name`=tbB.`name`;

3. SELECT * FROM tbA WHERE `name` LIKE BINARY ‘%中文%’;

4. INSERT INTO tbA (`bid`, `name`) (SELECT `id`, `name` FROM tbB);

5. INSERT INTO tbA (`bid`, `name`, `count`) VALUES (10, ‘abc’, 1) ON DUPLICATE KEY UPDATE `count`=`count`+1; # UNIQUE KEY `name` (`bid`,`name`)

6. SELECT *, COUNT(DISTINCT name) FROM table GROUP BY name