我有两张桌子
雇员
+=======+==========+
|id |level |
+=======+==========+
|1 |1 |
|2 |2 |
+=======+==========+
emp_level
+=======+========+==========+
|emp_id |level |date |
+=======+========+==========+
|1 |2 |2016-08-01|
|1 |1 |2012-08-01|
|2 |2 |2012-08-01|
+=======+========+==========+
我想看看employee
的关卡在最近的某个日期是否与emp_level
匹配,所以有点像这样
+=================+===============+===============+
|emp_level.emp_id |employee.level |emp_level.level|
+=================+===============+===============+
|1 |1 |2 |
|2 |2 |2 |
+=================+===============+===============+
我已尝试UNION
,但第二张表的结果位于不同的行,我不知道如何为所有emp_id执行此操作。我的疑问:
(select id, level from employee where id="957")
union all
(select emp_id as id, level from emp_level where
emp_id= "957" order by date desc limit 1)
答案 0 :(得分:1)
您可以尝试以下查询:
SELECT
E.id,
E.level,
maxDateLevelTable.level
FROM employee E
LEFT JOIN
(
SELECT
EL.*
FROM emp_level EL
INNER JOIN
(
SELECT
emp_id,
MAX(date) max_date
FROM emp_level
GROUP BY emp_id
) AS t
ON t.emp_id = EL.emp_id AND t.max_date= EL.date
) AS maxDateLevelTable
ON E.id = maxDateLevelTable.emp_id
ORDER BY E.id;
注意:如果找到LEFT JOIN
表中每位员工的条目,则可以将INNER JOIN
替换为emp_level
。
<强>解释强>
如果您单独运行此查询
SELECT
EL.*
FROM emp_level EL
INNER JOIN
(
SELECT
emp_id,
MAX(date) max_date
FROM emp_level
GROUP BY emp_id
) AS t
ON t.emp_id = EL.emp_id AND t.max_date= EL.date
然后您将从emp_level
表中获取每位员工的最新数据。
稍后在上面的查询结果和inner join
表之间设置一个employee
,以便从employee
表中获取相应的级别。