简体   繁体   中英

Joining two tables and display data from first table

I have two tables tblPatient, tblDropDowns tblpatient:

firstname   gender  patienttype
anil         1           3
Satheesh     1           4
Vinod        1           4 
Shashikanth  1           3
Srimani      2           3
Thanuja      2           4
Nandini      2           4
Vishu        2           3

and tblDropdowns:

id  Name
1   Male
2   Female
3   Inpatient
4   Outpatient

Now i want to display the patient table with gender and patient type as their significant names are connected to dropdown table. result table:

firstname          gender       patienttype
anil                male         inpatient
satheesh            male         outpatient
vinod               male          outpatient

please help me out.. thanks anil

In general it would be better avoid storing different things in the same table. However, you could join with subqueries that only contain the relevant records.

SELECT firstname, gender.Name AS gender, patienttype.Name As patienttype
FROM tblPatient p
INNER JOIN (SELECT id, Name 
            FROM tblDropdowns
            WHERE id IN (1, 2)) gender 
ON p.gender = gender.id
INNER JOIN (SELECT id, Name
            FROM tblDropdowns
            WHERE id > 2) patienttype
ON p.patienttype = patienttype.id

Please try out this.

select [column1], [column2] from tblpatient a, tbldropdowns b
where a.gender = b.id order by a.gender;

You could also use joins: Please refer this W3Schools SQL Link .

Hope this helps. Thanks.

Edit Maybe this query could be your solution:

    select a.firstname, b.name as 'gender', b.name as 'PatientType' 
    from tblpatient a, tbldropdowns b
    where a.gender = b.id and a.patienttype = b.id
    order by a.gender;

Thanks again. :-)

尝试如下:

 SELECT firstname, name, CASE WHEN (patienttype=3) THEN 'inpatient' ELSE 'outpatient' END as patienttype_text from tblpatient INNER JOIN tbldropdowns ON gender = id 

join your "tblDropdowns" table twice in your select query.

Please refer this link to understand join, http://www.w3schools.com/sql/sql_join_left.asp

select     tP.firstname,tG.Name gender,tPT.Name patienttype 
from       tblPatient tP 
left join  tblDropDowns tG 
on tG.id  = tP.gender 
left join  tblDropDowns tPT 
on tPT.id = tP.patienttype

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