查询选择联接表中的选择以及条件

时间:2018-09-07 07:06:32

标签: mysql sql

我有2个表关系。

这是雇员表:

"id"    "nik"        "namalengkap"  "tgl_join"  "resign_date"
"1" "1802012637"    "Agung"         "2013-02-18"    NULL
"2" "1801012633"    "Karyawan"      "2017-07-12"    "2018-08-06"
"3" "1804232684"    "Test Data"     "2018-08-21"    NULL

这是employee_historypositions表:

"id"    "nik"   "tgl_awal"  "tgl_akhir" "level_id"  "jabatan_id"    "departemen_id" "divisi_id" "direktorat_id" "publish"
"1" "1802012637"    "2017-05-12"    "2017-09-12"    "1" "[""3"",""4""]" "1" "2" "1" "1"
"2" "1802012637"    "2018-06-12"    "2018-07-12"    "2" "[4,2]" "1" "9" "3" "1"
"3" "1801012633"    "2018-07-26"    \N  "2" "[3,2]" "1" "11"    "3" "1"
"4" "1801012633"    "2018-09-10"    "2018-07-21"    "6" "[4]"   "1" "3" "1" "0"
"5" "1804232684"    "2018-07-21"    "2018-08-21"    "10"    "[4]"   "1" "2" "1" "1"

我想显示d,nik,nama lengkap,jabatan,级别,部门,divisi的数据有效于2018年7月

使用这种情况: 员工表中的条件:

  • join_date小于等于2018年的第7个月 和
  • resign_date等于NULL或resign_date大于2018年的第7个月

employee_historypositions表中的条件:

  • 发布等于1
  • tgl_awal不到2018年的第7个月
  • 如果结果之间存在重复数据,则必须显示最新的重复数据。

如何获取查询?

有人可以帮助我吗?谢谢

我尝试过此查询

SELECT a.*, b.nik, b.namalengkap,b.tgl_join, b.resign_date 
FROM employee_historypositions a
LEFT OUTER
JOIN 
employees b ON a.nik = b.nik
WHERE EXTRACT(YEAR_MONTH
FROM b.tgl_join) <= CONCAT("2018","07") AND b.resign_date IS NULL OR EXTRACT(YEAR_MONTH
FROM b.resign_date) > CONCAT("2018","07")

您可以从这里检查 http://sqlfiddle.com/#!9/700c31/1

,但数据全部显示在employee_historypositions中。 我只是不显示具有这种条件的数据。

  1. 发布等于1
  2. tgl_awal不到7个月2018
  3. 如果在显示的数据之间有2个重复数据,则必须显示最新数据。

2 个答案:

答案 0 :(得分:0)

这是获取两个表的所有列的快速方法。请注意,因为它包含更多唯一数据,所以请首先使用employee_historypositions。

select 
    t1.*,
    t2.*
from
    employee_historypositions t1
join
    employees table t2
on
    t1.nik = t2.nik;

然后,您可以替换*以获得所需的确切列。

因此,如果您想要第一个表中的一列,而第二个表中的一列,则可以:

select 
    t1.tgl_join,
    t2.tgl_awal
from
    employee_historypositions t1
join
    employees table t2
on
    t1.nik = t2.nik;

答案 1 :(得分:0)

join_date小于2018年的第7个月

`tgl_join` < '2018-07-01'

resign_date等于NULL或resign_date超过7个月2018年

`resign_date` IS NULL OR `resign_date` > '2018-07-01'

发布等于1

`publish` = 1

* tgl_awal少于7个月2018 *

`tgl_awal` < '2018-07-01'

如果在显示的数据之间有2个重复的数据,则必须显示最新的重复数据。

SELECT DISTINCT ...

因此,您的查询可能类似于:

--replace the ... by the fields you need.
SELECT DISTINCT emp.id, emp.nik, hist.jabatan_id ...
FROM `employees` emp
JOIN `employee_historypositions` hist
    ON `emp`.`nik` = `hist`.`nik`
WHERE (`emp`.`tgl_join` < '2018-07-01'
        AND (`emp`.`resign_date` IS NULL OR `emp`.`resign_date` > '2018-07-01')
        AND `hist`.`publish` = 1
        AND `hist`.`tgl_awal` < '2018-07-01')
相关问题