SQL 初级编程 分页显示数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL 初级编程 分页显示数据相关的知识,希望对你有一定的参考价值。
要求在过程中实现(今天刚学的while循环,能用上最好用上)
已有这么一张表 student
就这么两个字段 stu_id stu_name (stu_id 为10000条数据)
要求每页显示10条数据
就在数据库中完成即可
根据我提供的东西写一段代码 初期 考虑不用很全面 就实现分页就行
别的因素都可不考虑
不管了, 随便写个楼主试试吧~
--以下@page是页码编号.如果一定要用存储过程的话, 直接放到proc里面, 然后加个参数.
①:这个主要是针对stu_id顺序编号.而且, 具有唯一性的情况.
create proc proc_Pagination_1
(
@pageIndex int =1
)
as
declare int @page
set @page = 10*(@page-1)
select top 10 * from student where stu_id not in (select top @page stu_id from student)
②:这个跟stu_id是否为int类型, 是否有顺序编号无关.
create proc proc_Pagination
(
@pageIndex int =1
)
as
SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY stu_id Desc) AS Item,stuname FROM student) AS S WHERE Item BETWEEN (@pageIndex-1)*10+1 AND @pageIndex*10
修改了下下.
好了, 就提供这么两个简单的方法供LZ参考,希望有帮助吧~ 参考技术A 给你个我的存储过程做参考。
分页,用不上while.呵呵。
CREATE PROCEDURE UP_PARTY_ADMIN_AUDITLIST
@FILTER TINYINT,
@USERCODE VARCHAR(60),
@CATECODE VARCHAR(60),--0代表全部
@PAGESIZE INT,
@PAGEINDEX INT
AS
--DECLARE @CATES TABLE( CATECODE VARCHAR(60))
--INSERT INTO @CATES select * from f_split(@CATECODE,'|' )
create table #groups (groupcode varchar(60))
declare @groupcode varchar(60),
@rolecode varchar(60),
@offset int,
@s_offset varchar(20),
@s_pagesize varchar(20),
@strsql varchar(4000),
@strrc varchar(2000),
@fields varchar(1000),
@cond varchar(200),
@sort varchar(200),
@tables varchar(200),
@currdate char(10)
select @groupcode = groupcode from party_user where usercode=@usercode
select @rolecode = rolecode from party_usergroup where groupcode=@groupcode
if (@pageIndex < 1 ) set @pageIndex = 1
set @offset= @pagesize * ( @pageIndex- 1 )
set @s_offset = ltrim(rtrim(str(@offset)))
set @s_pagesize = ltrim(rtrim(str(@pagesize)))
set @currdate = convert(char(10),getdate(),102)
set @fields = ' *,(select catename from party_cate c where c.catecode=doc.catecode ) as catename,(case status when 1 then ''通过'' else ''未通过'' end ) as statusname,(select groupname from party_usergroup ug where ug.groupcode=doc.groupcode) as groupname '
if @rolecode ='admin'
begin
set @cond = ' 1=1 '
if ( @catecode <> '0' ) set @cond = @cond + ' and doc.catecode=''' + @catecode + ''''
if ( @filter <> 100 ) set @cond = @cond + ' and isnull(doc.status,0)=' + ltrim(rtrim(str(@filter))) + ' '
set @tables = ' party_document doc '
set @sort = ' order by id desc '
end
else
begin
insert into #groups (groupcode ) select groupcode from party_usergroup where parentcode=@groupcode --获取子组
set @cond = ' doc.groupcode=g.groupcode'
if ( @catecode <> '0' ) set @cond = @cond + ' and doc.catecode=''' + @catecode + ''''
if ( @filter <> 100 ) set @cond = @cond + ' and isnull(doc.status,0)=' + ltrim(rtrim(str(@filter))) + ' '
set @tables = ' party_document doc,#groups g '
set @sort = ' order by id desc '
end
--select * from #groups
set @strsql = 'select top top fields from tables where cond and doc.id not in (select top offset id from tables where cond sort) sort'
set @strrc = ' select count(1) as rc from tables where cond '
set @strsql = replace(@strsql,'top',@s_pagesize)
set @strsql = replace(@strsql,'tables',@tables)
set @strsql = replace(@strsql,'cond',@cond)
set @strsql = replace(@strsql,'offset',@offset)
set @strsql = replace(@strsql,'sort',@sort)
set @strsql = replace(@strsql,'fields',@fields)
set @strrc = replace(@strrc,'tables',@tables)
set @strrc = replace(@strrc,'cond',@cond)
exec (@strrc)
exec (@strsql)
GO 参考技术B 我刚看到是过程,呵呵,估计我的不行了,我给你发个新闻列表的例子吧,然后你就修改一下sql语句和字段名称就行了
<?
include "config.php";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="<?=$titles?>" />
<meta name="description" content="<?=$titles?>" />
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title><?=$titles?></title>
<style type="text/css">
<!--
.STYLE2 font-family: Arial, Helvetica, sans-serif
.page_break
height:25px;
font-size:12px;
line-height:25px;
.page_break strong
font-size:12px;
padding-left:8px;
padding-right:8px;
border:1px solid #FB9504;
background:#FFFBDE;
padding-top:4px;
padding-bottom:2px;
margin-left:6px;
.page_break a
padding-left:8px;
padding-right:8px;
border:1px solid #E1E1E1;
background:#fff;
font-size:12px;
padding-top:4px;
padding-bottom:2px;
color:#07519a;
text-decoration:none;
margin-left:6px;
.page_break a:hover
padding-left:8px;
padding-right:8px;
font-size:12px;
border:1px solid #FB9504;
background:#FFFBDE;
-->
</style>
</head>
<LINK href="images/client/css.css" type=text/css rel=stylesheet>
<body>
<?
$sql="select Id,pid,subject,instime,hit from news where types=1 order by pid desc";
$rec=mysql_query($sql,$conn);
$total=mysql_num_rows($rec);
$PageSize=10;
$TotalRows=$total;//总共有多少记录
$TotalPages=ceil($TotalRows/$PageSize);//总共有多少页
$Rowstring=" "."共有 ".$TotalPages." 页";
if(isset($_GET["showPage"]))
$showPage=intval($_GET["showPage"]);
else
$showPage=1;
$CurrentLocation.=$_SERVER["PHP_SELF"];
$sql0="select Id,pid,subject,instime,hit from news where types=1 order by pid desc"." limit ".($showPage-1)*$PageSize.",".$PageSize;
//echo $sql;
$result=mysql_query($sql0,$conn);
$tmpi=0;
?>
<table width="670" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="751" height="26" background="images/client/news_x.jpg" style="border-bottom:#e5e5e5 1px solid;border-left:#e5e5e5 1px solid;border-right:#e5e5e5 1px solid;border-top:#c75701 2px solid;"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr align="center">
<td width="47" class="enfont">NO.</td>
<td width="1"></td>
<td width="441" class="enfont">Subject</td>
<td width="1"></td>
<td width="110" class="enfont">Date</td>
<td width="1"></td>
<td width="65" class="enfont">Hit</td>
</tr>
</table></td>
</tr>
<tr>
<td height="280" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<? while($row=mysql_fetch_array($result)) ?>
<tr align="center" class="font">
<td width="47" height="24" style="border-bottom:#efefef 1px solid"><?=$row['pid']?></td>
<td width="1" style="border-bottom:#efefef 1px solid"></td>
<td width="441" align="left" style="border-bottom:#efefef 1px solid"><a href="news_detail.php?id=<?=$row['Id']?>" target="_blank">
<?=$row['subject']?>
</a></td>
<td width="1" style="border-bottom:#efefef 1px solid"></td>
<td width="110" style="border-bottom:#efefef 1px solid"><?=$row['instime']?></td>
<td width="1" style="border-bottom:#efefef 1px solid"></td>
<td width="65" style="border-bottom:#efefef 1px solid"><?=$row['hit']?></td>
</tr>
<?
$tmpi++;
?>
</table></td>
</tr>
<tr>
<td height="50" style="border-top:#c75701 2px solid;"><table cellspacing="0" cellpadding="0" width='100%' align="center">
<tr>
<td align="right" class="page_break"><?php if($showPage > 1)?>
<a href="<?php echo $CurrentLocation;?>?showPage=<?php echo $showPage-1;?>">上一页</a>
<?php
if($TotalPages==1)
else if($showPage==1&&$TotalPages>1)
echo "1";
for($p=2;$p<=5&&$p<=$TotalPages;$p++)?>
<a href="<?php echo $CurrentLocation;?>?showPage=<?php echo $p;?>"><?php echo $p;?></a>
<?php
else if($showPage<=5)
for($p=1;$p<=4+$showPage&&$p<=$TotalPages;$p++)
if($p==$showPage)
echo $p;?>
<?php else?>
<a href="<?php echo $CurrentLocation;?>?showPage=<?php echo $p;?>"><?php echo $p;?></a>
<?php else if($showPage>5)
for($p=$showPage-5;$p<=$showPage+4&&$p<=$TotalPages;$p++)
if($p==$showPage)
echo $p;?>
<?php else?>
<a href="<?php echo $CurrentLocation;?>?showPage=<?php echo $p;?>"><?php echo $p;?></a>
<?php ?>
<?php if(($showPage < $TotalPages)&&($TotalPages<>1))?>
<a href="<?php echo $CurrentLocation;?>?showPage=<?php echo $showPage+1;?>">下一页</a>
<?php ?>
<?php
echo $Rowstring;
?>
</td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>
SPark SQL编程初级实践
今下午在课上没有将实验做完,课下进行了补充,最终完成。下面附上厦门大学数据库实验室中spark实验官网提供的标准答案,以供参考。
三、实验内容和要求
1.Spark SQL 基本操作
将下列 json 数据复制到你的 ubuntu 系统/usr/local/spark 下,并保存命名为 employee.json。 { "id":1 ,"name":" Ella","age":36 } { "id":2,"name":"Bob","age":29 }
{ "id":3 ,"name":"Jack","age":29 }
{ "id":4 ,"name":"Jim","age":28 }
{ "id":5 ,"name":"Damon" }
{ "id":5 ,"name":"Damon" }
首先为 employee.json 创建 DataFrame,并写出 Scala 语句完成下列操作:创建 DataFrame
答案:
scala> import org.apache.spark.sql.SparkSession scala> val spark=SparkSession.builder().getOrCreate() scala> import spark.implicits._
scala> val df = spark.read.json("file:///usr/local/spark/test/employee.json")
(1) 查询 DataFrame 的所有数据答案:scala> df.show()
(2) 查询所有数据,并去除重复的数据
答案:scala> df.distinct().show()
(3) 查询所有数据,打印时去除 id 字段
答案:scala> df.drop("id").show() (4) 筛选age>20的记录答案:scala> df.filter(df("age") > 30 ).show()
(5) 将数据按 name 分组
答案:scala> df.groupBy("name").count().show()
(6) 将数据按 name 升序排列
答案:scala> df.sort(df("name").asc).show()
(7) 取出前 3 行数据
答案:scala> df.take(3) 或scala> df.head(3) (8) 查询所有记录的 name 列,并为其取别名为 username
答案:scala> df.select(df("name").as("username")).show()
(9) 查询年龄 age 的平均值
答案:scala> df.agg("age"->"avg") (10) 查询年龄 age 的最小值
答案:scala> df.agg("age"->"min")
2.编程实现将 RDD 转换为 DataFrame
源文件内容如下(包含 id,name,age),将数据复制保存到 ubuntu 系统/usr/local/spark 下,命名为 employee.txt,实现从 RDD 转换得到 DataFrame,并按 id:1,name:Ella,age:36 的格式
打印出 DataFrame 的所有数据。请写出程序代码。(任选一种方法即可)
1,Ella,36
2,Bob,29
3,Jack,29
答案:
假设当前目录为/usr/local/spark/mycode/rddtodf,在当前目录下新建一个目录 mkdir -p src/main/scala ,然后在目录 /usr/local/spark/mycode/rddtodf/src/main/scala 下新建一个
rddtodf.scala,复制下面代码;(下列两种方式任选其一)
方法一:利用反射来推断包含特定类型对象的RDD的schema,适用对已知数据结构的RDD 转换;
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder import org.apache.spark.sql.Encoder import spark.implicits._ object RDDtoDF { def main(args: Array[String]) { case class Employee(id:Long,name: String, age: Long) val employeeDF = spark.sparkContext.textFile("file:///usr/local/spark/employee.txt").map(_.split(",")).map(at tributes => Employee(attributes(0).trim.toInt,attributes(1), attributes(2).trim.toInt)).toDF() employeeDF.createOrReplaceTempView("employee") val employeeRDD = spark.sql("select id,name,age from employee") employeeRDD.map(t => "id:"+t(0)+","+"name:"+t(1)+","+"age:"+t(2)).show() } } |
方法二:使用编程接口,构造一个 schema 并将其应用在已知的 RDD 上。
import org.apache.spark.sql.types._import org.apache.spark.sql.Encoder import org.apache.spark.sql.Row object RDDtoDF { def main(args: Array[String]) { val employeeRDD = spark.sparkContext.textFile("file:///usr/local/spark/employee.txt") val schemaString = "id name age" val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable = true)) val schema = StructType(fields) val rowRDD = employeeRDD.map(_.split(",")).map(attributes => Row(attributes(0).trim, attributes(1), attributes(2).trim)) val employeeDF = spark.createDataFrame(rowRDD, schema) employeeDF.createOrReplaceTempView("employee") val results = spark.sql("SELECT id,name,age FROM employee") results.map(t => "id:"+t(0)+","+"name:"+t(1)+","+"age:"+t(2)).show() } } |
在目录/usr/local/spark/mycode/rddtodf 目录下新建 simple.sbt,复制下面代码:
name := "Simple Project" version := "1.0" scalaVersion := "2.11.8" libraryDependencies += "org.apache.spark" % "spark-core" % "2.1.0" |
在目录/usr/local/spark/mycode/rddtodf 下执行下面命令打包程序
/usr/local/sbt/sbt package |
|
最后在目录/usr/local/spark/mycode/rddtodf 下执行下面命令提交程序 |
|
/usr/local/spark/bin/spark-submit --class " RDDtoDF /usr/local/spark/mycode/rddtodf/target/scala-2.11/simple-project_2.11-1.0.jar |
" |
在终端即可看到输出结果。
3. 编程实现利用 DataFrame 读写 MySQL 的数据
(1) 在 MySQL 数据库中新建数据库 sparktest,再建表 employee,包含下列两行数据;表 1 employee 表原有数据
id |
name |
gender |
|
age |
1 |
Alice |
F |
|
22 |
2 |
John |
M |
|
25 |
答案:
mysql> create database sparktest; mysql> use sparktest;
mysql> create table employee (id int(4), name char(20), gender char(4), age int(4)); mysql> insert into employee values(1,‘Alice‘,‘F‘,22); mysql> insert into employee values(2,‘John‘,‘M‘,25);
(2) 配置 Spark通过 JDBC 连接数据库MySQL,编程实现利用 DataFrame 插入下列数据到 MySQL,最后打印出 age 的最大值和 age 的总和。表 2 employee 表新增数据
id |
|
name |
|
gender |
|
age |
3 |
|
Mary |
|
F |
|
26 |
4 |
|
Tom |
|
M |
|
23 |
答案:假设当前目录为/usr/local/spark/mycode/testmysql,在当前目录下新建一个目录 mkdir -p src/main/scala ,然后在目录 /usr/local/spark/mycode/testmysql/src/main/scala 下新建一个 testmysql.scala,复制下面代码;
import java.util.Properties import org.apache.spark.sql.types._ import org.apache.spark.sql.Row object TestMySQL { def main(args: Array[String]) { val employeeRDD = spark.sparkContext.parallelize(Array("3 Mary F 26","4 Tom M 23")).map(_.split(" ")) val schema = StructType(List(StructField("id", IntegerType, true),StructField("name", StringType, true),StructField("gender", StringType, true),StructField("age", IntegerType, true))) val rowRDD = employeeRDD.map(p => Row(p(0).toInt,p(1).trim, p(2).trim,p(3).toInt)) val employeeDF = spark.createDataFrame(rowRDD, schema) val prop = new Properties() prop.put("user", "root") prop.put("password", "hadoop") prop.put("driver","com.mysql.jdbc.Driver") employeeDF.write.mode("append").jdbc("jdbc:mysql://localhost:3306/sparktest", sparktest.employee", prop) val jdbcDF = spark.read.format("jdbc").option("url", "jdbc:mysql://localhost:3306/sparktest").option("driver","com.mysql.jdbc.Driver").optio n("dbtable","employee").option("user","root").option("password", "hadoop").load() jdbcDF.agg("age" -> "max", "age" -> "sum") } } |
在目录/usr/local/spark/mycode/testmysql 目录下新建 simple.sbt,复制下面代码:
name := "Simple Project" version := "1.0" scalaVersion := "2.11.8"
libraryDependencies += "org.apache.spark" % "spark-core" % "2.1.0" |
|
在目录/usr/local/spark/mycode/testmysql 下执行下面命令打包程序 |
|
/usr/local/sbt/sbt package |
|
最后在目录/usr/local/spark/mycode/testmysql 下执行下面命令提交程序 |
|
/usr/local/spark/bin/spark-submit --class " TestMySQL /usr/local/spark/mycode/testmysql/target/scala-2.11/simple-project_2.11-1.0.jar |
" |
在终端即可看到输出结果。
以上是关于SQL 初级编程 分页显示数据的主要内容,如果未能解决你的问题,请参考以下文章