【问题标题】:How to write a Mysql Query to select data from specific column?如何编写 Mysql 查询以从特定列中选择数据?
【发布时间】:2015-06-10 19:15:53
【问题描述】:

在这里我想清楚地解释我的问题

这是我的桌子

id  company_ID  Employee_ID Name        Relationship    Dob     Age Gender       
1   EMPL        00001       Choodamani  Spouse      11-Aug-66   49  Female            
2   EMPL        00001       Komala      Mother      30-Oct-39   76  Female            
3   EMPL        00001       Varshini    Daughter    29-Apr-04   11  Female            
4   EMPL        00001       Vasudevan   Employee    15-Jul-62   53  Male    
5   EMPL        00002       Siddharth   Son         1-Jun-00    15  Male              
6   EMPL        00002       Poongavanam Mother      21-Oct-39   76  Female            
7   EMPL        00002       Aruna       Spouse      16-Sep-68   47  Female            
8   EMPL        00002       Abirami     Daughter    7-May-97    18  Female            
9   EMPL        00002       Murali      Employee    7-Oct-67    48  Male

请阅读以下场景。那是我的确切问题

在这里,如果我选择一个 id 5,使用 id 5,我需要获取 employee_id,使用该employee_id 我需要获取所有属于该employee_id 的员工的姓名

如何为这种情况编写 mysql 查询

【问题讨论】:

  • 在您的架构中,员工如何相互归属?
  • 另外,为什么要先用id,然后再用员工ID,为什么不直接给出员工ID并获取所有记录?请更正您的表格架构。

标签: php mysql


【解决方案1】:

使用子查询:

SELECT * 
FROM TableName
WHERE Employee_ID=(SELECT Employee_ID 
                   FROM TableName 
                   WHERE id=5)

结果:

id  company_ID  Employee_ID Name        Relationship    Dob                         Age  Gender
5   EMPL        2           Siddharth   Son             June, 01 2000 00:00:00      15  Male
6   EMPL        2           Poongavanam Mother          October, 21 2039 00:00:00   76  Female
7   EMPL        2           Aruna       Spouse          September, 16 1968 00:00:00 47  Female
8   EMPL        2           Abirami     Daughter        May, 07 1997 00:00:00       18  Female
9   EMPL        2           Murali      Employee        October, 07 1967 00:00:00   48  Male

SQL Fiddle 中的示例结果。

【讨论】:

    【解决方案2】:

    你可以试试这个查询 -

    SELECT * 
    FROM `tablename`
    WHERE `employee_id` = (SELECT `employee_id` 
                             FROM `tablename`  
                             WHERE `id` = 5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 2016-01-29
      • 2017-05-01
      • 1970-01-01
      相关资源
      最近更新 更多