简体   繁体   中英

How to write a Mysql Query to select data from specific column?

Here i like to explain my problem clearly

This is my table

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

please read the below scenario. thats my exact problem

Here if i select a id 5 , using id 5 i need to get employee_id , using that employee_id i need to get name of employees who all belongs to that employee_id

How can i write mysql query for this scenario

Use a subquery:

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

Result:

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

Sample result in SQL Fiddle .

You can try this query -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM