【问题标题】:How To Get Highest Education Using MySQL?如何使用 MySQL 获得高等教育?
【发布时间】:2016-05-04 02:13:07
【问题描述】:

我在尝试获得最高教育结果时遇到问题。例如我有 5 张桌子。

员工

+-----------+----------+
| STAFF ID  | NAME     |
+-----------+----------+
|   001     | Ramesh   |
|   002     | Khilan   |
|   003     | Kaushik  |
|   004     | Chaitali |
|   005     | Hardik   |
|   006     | Komal    |
|   007     | Muffy    |
+-----------+----------+

文凭

+-----------+-------------------------+
| STAFF ID  |          DIPLOMA        |
+-----------+-------------------------+
|   001     | Diploma in IT           |
|   003     | Diploma in Multimedia   |
|   004     | Diploma in Multimedia   |
|   005     | Diploma in IT           |
+-----------+-------------------------+

学位

+-----------+-------------------------+
| STAFF ID  |          DEGREE         |
+-----------+-------------------------+
|   002     |  Degree in Science      |
|   003     |  Degree in Multimedia   |
+-----------+-------------------------+

大师

+-----------+-------------------------+
| STAFF ID  |          MASTER         |
+-----------+-------------------------+
|   006     |  Master in Arts         |
|   007     |  Master in Business     |
+-----------+-------------------------+

如何通过 MySQL 中的最高学历筛选员工?例如,我想搜索只有文凭的员工,不希望同时拥有文凭和学位的员工姓名 Kaushik 显示在我的搜索结果中?

【问题讨论】:

  • 代码片段用于 HTML/JS,因此我将 sn-ps 拆分为 code sample 块并将表名格式化为标题。

标签: php mysql


【解决方案1】:

您可以使用 COALESCE 函数返回第一个非空值 然后按顺序传递您的硕士、学位、文凭,以便它返回第一个非空值,即像这样的最高教育水平

SELECT s.staff_id,
       s.name,
       COALESCE(m.master,d.degree,di.diploma) AS highest_education
FROM staff s
LEFT JOIN master m on s.staff_id = m.staff_id
LEFT JOIN degree d on s.staff_id = d.staff_id
LEFT JOIN diploma di on s.staff_id = di.staff_id

然后要过滤掉文凭,您可以像这样添加HAVING highest_education LIKE "Diploma%"

SELECT s.staff_id,
       s.name,
       COALESCE(m.master,d.degree,di.diploma) AS highest_education
FROM staff s
LEFT JOIN master m on s.staff_id = m.staff_id
LEFT JOIN degree d on s.staff_id = d.staff_id
LEFT JOIN diploma di on s.staff_id = di.staff_id
HAVING highest_education LIKE "Diploma%"

http://sqlfiddle.com/#!9/e1e47/3

【讨论】:

    【解决方案2】:

    就这么简单.. 但我建议您花一些时间学习如何执行基本的 sql 查询.. 有很多有用的资源可以帮助您入门。

    SELECT * FROM Staff 
    WHERE `STAFF ID` IN (SELECT `STAFF ID` FROM Diploma) 
    AND `STAFF ID` NOT IN (SELECT `STAFF ID` FROM Degree)
    

    【讨论】:

      【解决方案3】:

      还有一种可能:

      select staff.*,diploma education
        from staff
             left join diploma using(`staff id`)
             left join degree using(`staff id`)
             left join master using(`staff id`)
        where diploma is not null
          and degree is null
          and master is null;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-29
        • 1970-01-01
        • 1970-01-01
        • 2015-08-29
        • 1970-01-01
        • 1970-01-01
        • 2012-06-13
        • 1970-01-01
        相关资源
        最近更新 更多