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

时间:2013-10-07 22:23:42

标签: 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次相同的项目,我得到1项4次。所以如果任何项目超过1

,我想要获得1项

任何人都知道这件事吗?

1 个答案:

答案 0 :(得分:1)

在查询结尾处使用LIMIT 1

此外,如果您获得2个或更多相等的行,则可以使用 DISTINCT GROUP 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

在您的情况下,您可以使用distinct:

$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

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