如何加入2个表并订购它们?

时间:2014-04-03 10:20:27

标签: mysql

我有2个表:_divions_employee。在_employee中,division列中的id_division_division。我需要先按_division订单订购。

此表格有一列order。我已经尝试过这个SQL语句,但它并没有做太多的事情:

SELECT
    e . *
FROM
    `_employee` AS  `e`
JOIN
    `_division` AS d
ORDER BY
    d.order,
    e.division,
    e.order

2 个答案:

答案 0 :(得分:0)

您缺少ON子句。试试这个

SELECT e.* 
FROM _employee AS e 
JOIN _division AS d ON d.id_division = e.division
 //                ^^^^  Missing
ORDER BY e.order

答案 1 :(得分:0)

以下查询可能有所帮助。 (假设有没有员工的部门)

    with employee as
(
 select 'NISHA' ENAME, '10' EDIV FROM DUAL
 UNION
 SELECT 'ABC' ENAME, '10' EDIV FROM DUAL 
 UNION
 SELECT 'DEF' ENAME, '15' EDIV FROM DUAL
 UNION
 SELECT 'GHI' ENAME, '20' EDIV FROM DUAL
),
DIVISION AS
(
  SELECT '10' DIV_ID, 'INFO-TECH' DIV_DESC FROM DUAL 
  UNION
  SELECT '15' DIV_ID, 'HUMAN RESOURCES' DIV_DESC FROM DUAL
  UNION
  SELECT '20' DIV_ID, 'SALES' DIV_DESC FROM DUAL
  UNION
  SELECT '25' DIV_ID, 'RESEARCH' DIV_DESC FROM DUAL
)
  SELECT *
  FROM EMPLOYEE, DIVISION WHERE
  employee.EDIV (+) = DIVISION.DIV_ID 
  ORDER BY DIV_DESC, ENAME

如果所有员工肯定都有分部,那么请使用employee.EDIV = DIVISION.DIV_ID而不是employee.EDIV(+)= DIVISION.DIV_ID