php - 如果相同 id 项目超过 1 个,如何从 mysql 获取 1 个项目

标签 php mysql

我想做。如果相同的 id 内容超过 1,则仅从 mysql 获取 1 项。我不知道该怎么做。 下面是我的 MySQL 查询。

$myboxexi=mysql_query("select box.upload_type,box.id,box.box_type,box.page_name,box.title,box.connect,box.type,box.uid,box.description,box.image,box.url,box.status,box.date,box.time
from {$statement} where pages.uid='".$session_id."' or catsb.uid='".$session_id."' and box.status='".$approval."' order by box.id desc limit {$startpoint} , {$limit}");

问题是我正在通过(box.id)从另一个表获取数据,并且某些表有 4 次相同的项目,而我 4 次获得 1 项。所以我想要获取 1 件(如果有任何元素超过 1 件)

有人知道这个吗?

最佳答案

在查询末尾使用 LIMIT 1

此外,如果您获得 2 个或更多相同的行,您可以使用 DISTINCTGROUP BY 来获得唯一的行

DISTINCT 语法:

SELECT DISTINCT t1.field1, t1.field2, t1.field3
FROM table1 AS t1, table2 as t2
WHERE t1.field1=t2.field1
AND t1.field1=value1

GROUP BY 语法:

SELECT t1.field1, t1.field2, t1.field3
FROM table1 AS t1, table2 as t2
WHERE t1.field1=t2.field1
AND t1.field1=value1
GROUP BY t2.field2

根据您的情况,您可以使用不同的:

$query = "SELECT DISTINCT box.upload_type, box.id, box.box_type, box.page_name, ";
$query .= "box.title, box.connect, box.type, box.uid, box.description, ";
$query .= "box.image, box.url, box.status, box.date, box.time ";
$query .= "FROM {$statement} ";
$query .= "WHERE pages.uid='".$session_id."' ";
$query .= "OR catsb.uid='".$session_id."' ";
$query .= "AND box.status='".$approval."' ";
$query .= "ORDER BY box.id DESC ";
$query .= "LIMIT {$startpoint} , {$limit}";

$myboxexi=mysql_query($query);

有关DISTINCT的更多信息,您可以在这里找到:http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html

有关GROUP BY的更多信息,您可以在这里找到:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

尝试编写格式化代码。您和其他程序员很容易调试。

关于php - 如果相同 id 项目超过 1 个,如何从 mysql 获取 1 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19235836/

相关文章:

php - 在 JavaScript 中使用 smarty 数组

javascript - 为什么 AJAX 成功调用中的代码不起作用?

php - 使用 LEFT JOIN 通过 Form 插入 MySQL

php - 在不刷新页面的情况下将数据发送到数据库

php - 我可以在 php 中编辑 mysqli_result 对象吗?

PHP:什么是 Getter 和 Setter?

php - 使用 GD 库制作图像灰度

php - 根据数据库字段创建 HTML 表单

Mysql Insert into with select from myisam to innodb

php - WordPress 插件 : How to resolve "Call to undefined function add_action() as well as add_action()"?