超級變態的MySQL語句[2012-9-20]

-- mysql多表授權sql腳本製作
select concat("grant all privileges on studypaydb.",table_name," to 'sp'@'localhost';")
from tables
where table_schema='mydb' and table_name like 'sh_%'
into outfile 'D:/grant.sql';

-- 並查詢
select u1.id,u1.pid,u1.content,u2.haveoptions
from (
select id,pid,content,type_id
from sh_ques
where id in (1,4)
union
select s1.id,s1.pid,s1.content,s1.type_id
from sh_ques s1,sh_ques s2
where s1.pid=s2.id
) u1,sh_ques_type u2
where u1.type_id=u2.id;

-- mysql替代變量應用示例
select @tpid:=1;
select @tpid;

set @tpid=1;
select @tpid;

-- mysql 使用替代變量
set @tpid=2;
set @num=1;

prepare stmt from "
select id,pid,content,type_id
from sh_ques
where type_id=? and pid=0
order by rand()
limit ?";

EXECUTE STMT USING @tpid, @num;

--隨機取每組的一條記錄
SELECT
type_id,
(SELECT id from sh_ques sub
WHERE type_id = main.type_id ORDER BY rand()
LIMIT 0,1) AS Rstr
FROM
sh_ques main
GROUP BY type_id;

--mysql如何加行號
SET @id = 0;
SELECT (@id := @id + 1) ID, name FROM tblName;

-- 分組查詢每組id最大的兩條記錄
SELECT a.*
FROM sh_ques a
LEFT JOIN  sh_ques b ON a.type_id=b.type_id AND a.id>b.id
group by a.id,a.type_id,a.content
having count(b.id)<2
ORDER BY a.type_id asc,a.id;

-- mysql數據分組後重新加行號
set @id:=0;
set @type_id:=0;  -- 任意值,最好與type_id同類型

SELECT IF(@type_id=a.type_id,@id := @id + 1,@id:=1 and @type_id:=a.type_id) rID,a.* from (select * from sh_ques order by type_id desc) a

-- mysql 有則更新,無則插入
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

-- mysql insert ..select語句
insert into sh_record_details(qid,rid,my_answer,is_right)
select qid,rid,my_answer,if(my_answer=(select answer from sh_ques b where b.id=a.qid),1,0)
from sh_myans a

-- mysql update..select
update sh_record a
set a.score=(select b.score from sh_ques b where a.qid=b.id)
where is_right=1;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章