0

I have two tables like below:

TableA --> categoryId(pk), categoryParentId, catName
TableB --> empId(pk), categoryId, empName, empDesignation

enter image description here

I want to get all catName with respective categoryId from TableA where categoryId=2 of TableB is equal to categoryParentId=2 of TableA. Please help.

Result:

1002   SE
1003   MD
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shan
  • 435
  • 6
  • 19

5 Answers5

0

Something like this?

SELECT DISTINCT catName FROM TABLEA WHERE categoryParentId IN (SELECT DISTINCT categoryID from TABLEB);
ryanbwork
  • 2,123
  • 12
  • 12
  • Thanks for the code. Little change I want in the query i.e. categoryId of tableB is 2 and select catName as well as respective categoryId. – Shan Aug 30 '12 at 21:29
0

Solution with INNER JOIN:

select TableA.catName
from TableA
inner join TableB on TableA.categoryParentId = TableB.categoryId

Using INNER JOIN is the recommended way to use for joining tables (as opposed to SELECT ... FROM TableA, TableB ...)

See:


Answering your comment (I assume that you wanted the categoryId from TableA):

select TableA.catName, TableA.categoryId
from TableA
inner join TableB on TableA.categoryParentId = TableB.categoryId
where TableB.categoryId = 2
Community
  • 1
  • 1
Christian Specht
  • 35,843
  • 15
  • 128
  • 182
  • I want categoryId of tableB equal to 2 and select catName as well as respective categoryId. – Shan Aug 30 '12 at 22:21
0

I hope this query will fulfill your need

    SELECT TABLEA.CATNAME AS CATEGORY
    from TABLEB INNER JOIN TABLEA 
    ON TABLEA.CATEGORYPARENTID = TABLEB.CATEGORYID
MD. Sahib Bin Mahboob
  • 20,246
  • 2
  • 23
  • 45
0

another method...

SELECT 
  catname
from
  tablea a INNER JOIN
  tableb b ON 
    a.categoryParentID = b.categoryID
  group by
  catname
Rince Thomas
  • 4,158
  • 5
  • 25
  • 44
Beth
  • 9,531
  • 1
  • 24
  • 43
-1

This should do the trick

SELECT tableA.catName
 FROM tableA, tableB
WHERE tableB.categoryId = table1.categoryParentId
  AND tableB.categoryId = 2;

If you want the unique catNames, you can use

SELECT distinct tableA.catName
 FROM tableA, tableB
WHERE tableB.categoryId = table1.categoryParentId
  AND tableB.categoryId = 2;
Romain
  • 1,292
  • 1
  • 10
  • 14
  • For categoryId of tableB equal to 2 and select catName as well as respective categoryId. – Shan Aug 30 '12 at 22:20