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