Question

I have two tables and I have to select the values from two tables based on the query

I have two tables like tab1,tab2 and each having same columns name,age,job,gender. and in tab 2 I have extra column place

I have to select all values from tab1 and tab2 where the gender is male

how to do it?

SELECT tab1.name,tab1.gender,tab1.age,tab2.place FROM tab1 INNER JOIN tab2 ON tab1.gender=mhdetail.gender where gender='male';

is this correct?

Était-ce utile?

La solution 2

You're not looking for a join. You want an Union:

SELECT *
FROM MyTable1
WHERE Gender = 'Male'

UNION -- Or 'UNION ALL' if you want duplicates.

SELECT *
FROM MyTable2
WHERE Gender = 'Male'

A join would be used if you had 2 tables, and wanted info from the 2 tables, but only one table would contain the gender:

SELECT *
FROM   MyTable1
JOIN   MyTable2 ON MyTable1.ID = MyTable1.ID
WHERE  MyTable1.Gender = 'Male'

Autres conseils

You need to be more specific on JOIN condition(s). If you don't have ids in both tables, but combination of name, gender, age is unique, then you can do it like this

SELECT t1.name,
       t1.gender,
       t1.age,
       t2.place 
  FROM tab1 t1 LEFT JOIN 
       tab2 t2 ON t1.gender = t2.gender AND
                  t1.name = t2.name AND
                  t1.age = t2.age    
 WHERE t1.gender='male';

Here is SQLFiddle

Your query will results in many duplicate rows. Because it will become many to many relationship. If these two tables are related by any means like primary and foreign key relationship then join using these keys. Otherwise use union as posted in above answer.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top