0

我有 1 个查询来借助内部连接从三个表中获取记录。

table name

tbl_emp as emp
tbl_sal as sal
tbl_address as addr

fields from 3 tables

Schema:

tbl_emp - empid,name,comp_id
tbl_sal - empid - emp_type
tbl_address - emp_type

询问

SELECT emp.empid, emp.name, sal.salary, addr.address 
from tbl_emp as emp 
INNER JOIN tbl_sal as sal 
  ON emp.empid = sal.empid 
INNER JOIN tbl_address as addr 
  ON addr.emp_type = sal.emp_type 
where comp_id = '114';

结果显示:

1 abc 1000 test
1 abc 1000 test
1 abc 1000 test
1 abc 1000 test
1 abc 1000 test
2 xyz 2500 main
2 xyz 2500 main
2 xyz 2500 main
2 xyz 2500 main
2 xyz 2500 main

我想要这样的结果:

1 abc 1000 test
2 xyz 2500 main

请帮助我。

4

5 回答 5

2

根据您的示例数据,您应该能够使用DISTINCT

SELECT DISTINCT emp.empid, 
  emp.name,
  sal.salary,
  addr.address 
from tbl_emp as emp 
INNER JOIN tbl_sal as sal 
  ON emp.empid = sal.empid 
INNER JOIN tbl_address as addr 
  ON addr.emp_type = sal.emp_type 
where comp_id = '114';

DISTINCT应用于所有数据列,并将删除任何重复项。您的有限样本将允许应用此方法。

您也可以使用GROUP BY来获取结果。如果您应用,我的建议是GROUP BY将其应用于SELECT列表中的每个项目:

SELECT emp.empid, 
  emp.name,
  sal.salary,
  addr.address 
from tbl_emp as emp 
INNER JOIN tbl_sal as sal 
  ON emp.empid = sal.empid 
INNER JOIN tbl_address as addr 
  ON addr.emp_type = sal.emp_type 
where comp_id = '114'
GROUP BY emp.empid, emp.name, sal.salary, addr.address;

MySQL 使用一个扩展来GROUP BY允许选择列表中的项目是非聚合的并且不包含在GROUP BY子句中。然而,这可能会导致意外的结果,因为 MySQL 可以选择返回的值。(参见MySQL 对 GROUP BY 的扩展

来自 MySQL 文档:

MySQL 扩展了 GROUP BY 的使用,以便选择列表可以引用未在 GROUP BY 子句中命名的非聚合列。...您可以使用此功能通过避免不必要的列排序和分组来获得更好的性能。但是,这主要在每个未在 GROUP BY 中命名的非聚合列中的所有值对于每个组都相同时很有用。服务器可以自由地从每个组中选择任何值,因此除非它们相同,否则选择的值是不确定的。此外,从每个组中选择值不会受到添加 ORDER BY 子句的影响。在选择了值之后对结果集进行排序,并且 ORDER BY 不会影响服务器选择的值。

于 2013-03-04T09:54:37.783 回答
1

使用分组:

SELECT emp.empid,emp.name,sal.salary,addr.address from tbl_emp as emp INNER JOIN tbl_sal as sal ON emp.empid = sal.empid INNER JOIN tbl_address as addr ON addr.emp_type = sal.emp_type where comp_id = '114'
group by emp.empid,emp.name,sal.salary,addr.address
于 2013-03-04T09:53:34.023 回答
1

试试这个

SELECT  emp.empid,
        emp.name,
        sal.salary,
        addr.address 
FROM tbl_emp as emp 
INNER JOIN tbl_sal as sal 
    ON emp.empid = sal.empid 
INNER JOIN tbl_address as addr 
    ON addr.emp_type = sal.emp_type 
WHERE comp_id = '114'  
GROUP BY empid;
于 2013-03-04T09:53:51.527 回答
0

DISTINCT 关键字会做你想做的事,它会确保过滤掉重复项

SELECT DISTINCT emp.empid,emp.name,sal.salary,addr.address from tbl_emp as emp INNER JOIN tbl_sal as sal ON emp.empid = sal.empid INNER JOIN tbl_address as addr ON addr.emp_type = sal.emp_type where comp_id = '114';

但是,如果您得到重复项,您可能希望确保您的查询确实按照您的想法执行,否则如果您的结果集中存在真正的重复项(而不是由您的查询创建的重复项),您可能会遇到使用 DISTINCT 的问题。

于 2013-03-04T09:55:03.090 回答
0

尝试group by emp.empid

SELECT emp.empid,emp.name,sal.salary,addr.address from tbl_emp as emp INNER JOIN tbl_sal as sal ON emp.empid = sal.empid INNER JOIN tbl_address as addr ON addr.emp_type = sal.emp_type where comp_id = '114'  group by emp.empid ;
于 2013-03-04T09:56:10.420 回答