我有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
请帮我解决这个问题。
答案 0 :(得分: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 Extensions to GROUP BY)
来自MySQL文档:
MySQL扩展了GROUP BY的使用,因此选择列表可以引用GROUP BY子句中未命名的非聚合列。 ...您可以通过避免不必要的列排序和分组来使用此功能来获得更好的性能。但是,当GROUP BY中未命名的每个非聚合列中的所有值对于每个组都相同时,这非常有用。服务器可以自由选择每个组中的任何值,因此除非它们相同,否则所选的值是不确定的。此外,添加ORDER BY子句不会影响每个组中值的选择。选择值后会对结果集进行排序,而ORDER BY不会影响服务器选择的值。
答案 1 :(得分:1)
使用group by:
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
答案 2 :(得分: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;
答案 3 :(得分: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时遇到问题,如果结果集中存在真正的重复项(而不是您创建的那些重复项)查询)。
答案 4 :(得分: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 ;