php - 查询连接给我重述结果 mysql php

标签 php mysql

我在 mysql 中有一个查询返回我重复的结果我想要结果唯一。例如在我的例子中我有公司名称它返回我重复的名字,id。

SELECT 
      company.name,
      company.id,
      branchInfo.name,
      branches.visible 
FROM branches  
INNER JOIN users branchInfo ON branches.branchId=branchInfo.id 
INNER JOIN users company ON branches.companyId=company.id   
WHERE branches.visible=1 

它会返回多次重复的数据,所以我希望它是唯一的。

最佳答案

您可以使用 DISTINCTGROUP BY ,它们不一样,但在您的示例中,您会得到相同的结果。

如果您只想删除重复项,请使用 DISTINCT。如果您想应用聚合运算符,请使用 GROUPY BY,例如:AVG、MAX、MIN、SUM 和 COUNT

试试这个:

SELECT 
  company.name,
  company.id,
  branchInfo.name,
  branches.visible 
FROM branches  
INNER JOIN users branchInfo ON branches.branchId=branchInfo.id 
INNER JOIN users company ON branches.companyId=company.id   
WHERE branches.visible=1 
GROUPY BY company.name

或者这个:

SELECT 
  DISTINCT(company.name),
  company.id,
  branchInfo.name,
  branches.visible 
FROM branches  
INNER JOIN users branchInfo ON branches.branchId=branchInfo.id 
INNER JOIN users company ON branches.companyId=company.id   
WHERE branches.visible=1;

Group by : clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and fetching only unique records.

更新

关于您关于联接的问题。

enter image description here

关于php - 查询连接给我重述结果 mysql php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43892299/

相关文章:

mysql - PHP/Codeigniter - 全文搜索时出现 MySQL 错误?

php - 如何保护 Joomla 并防止被黑客入侵?

MySQL 全文(非)搜索

javascript - 是否可以在 PHP 的 Mail 功能中添加 CSS?

PHP 删除数组键

mysql - SQL返回错误: Unknown column "g" in 'field list'

c# - 在 C# 中使用 iTextSharp 和 asp 图像调整数据库中的图像大小

mysql - 如何创建与 MySQL Admin 的连接?

php - MySQL 查询 - 从两个记录集中选择

php - Doctrine 2 WHERE IN 子句使用实体集合