如何从数据库限制5中选择行以及其他导致一个字符串?

时间:2015-03-05 23:47:24

标签: php mysql sql select rows

好的,首先抱歉我的英语不好,我会尝试更好地解释我的需要。

     Name       Number       tid


1    topic1     25           1
2    topic2     23           1
3    topic3     20           1
4    topic4     19           1
5    topic5     17           1
6    topic6     15           1
7    topic7     12           1
8    topic8     9            1

现在我想在数字和其他(6,7,8)的一个字符串中显示前5个订单,如

1    topic1     25           1
2    topic2     23           1
3    topic3     20           1
4    topic4     19           1
5    topic5     17           1
6    Other      15+12+9      1

你现在明白我需要什么吗? 再次抱歉我的英语不好

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT * FROM <tablename> ORDER BY num LIMIT 5;

SELECT *子句从表中的所有列请求适当的数据。如果您只想要来自某些列的数据,例如id,name和num,则列出那些以逗号分隔的列而不是星号。

FROM子句指定了获取数据的表的名称 - 因为我不知道你的是什么,所以你必须把它放在自己身上。

ORDER BY和LIMIT执行它们的声音 - 指定数据的排序方式,并限制查询返回的行数。

我希望有所帮助!如果您正在寻找有关SQL的基本信息,请查看http://www.w3schools.com/sql/

答案 1 :(得分:0)

这是查询.....但非常基本。 尝试自己记录MySQL的基础知识。

SELECT * FROM table ORDER BY num ASC LIMIT 5

答案 2 :(得分:0)

您可以在php中使用MySQLi驱动程序:

使用get或post参数:

<?php

if( isset($_REQUEST['page']){
    $page = $_REQUEST['page'];
}else{
    $page = 1;
}

//connect to db
$db = new mysqli('host', 'user', 'pass', 'db');
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$query = "SELECT * FROM table ORDER BY num DESC";

if (!isset($_REQUEST['all'])){
    $query = $query . " LIMIT 5 OFFSET " . 5 * ($page - 1);
}
if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}
?>
<html>
<head>
...
</head>
<body>
  <table>
    <tr>
      <th>Name</th>
      <th>Num</th>
      <th>Id</th>
    </tr>
    <tbody>
    <?php while($row = $result->fetch_assoc()){ ?>
    <tr>
      <td><?php $row['name'] ?></td>
      <td><?php $row['num'] ?></td>
      <td><?php $row['id'] ?></td>
    </tr>
    <?php } ?>
    </tbody>
  </table>
  <?php
      $result->free();
      $db->close();
  ?>
  <a href="?all">all</a>
  <a href="?page=<?php $page - 1 ?>">prev</a>
  <a href="?page=<?php $page + 1 ?>">next</a>
...
</body>
</html>

如果我没有错过任何它应该有效。

如果我弄错了,请告诉我,我希望这会对你有所帮助。