Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Data from two tables where ID on both tables are same

Tags:

mysql

Okay I have two tables called subobject: parentID, objectName, subID(primary) and subrelation: ID, className

parentID | objectName | subID            ID| className|
_____________________________            ______________
    84   |   Test     |   14             14|    BOM      
    84   |   Test2    |   15             15|    Schematics

I want to match SubID with ID from both tables depending if they are the same values, then iterate all the values that are the same. Whats the query to do this in Mysql.

this is how I want it to look:

subobjectNAME:
     --RelatedClass
     --RelatedClass2

etc.

I know this is has something to do with JOIN and this is the mysql Query im using but its not working

"SELECT * from subrelation inner join subobject on subrelation.ID = subobject.subID"

also my while loop to grab this

while($join = mysqli_fetch_assoc($join))
like image 411
Cubatown Avatar asked May 24 '13 15:05

Cubatown


1 Answers

JOIN the two tables:

SELECT
  so.objectName,
  sr.ClassName
FROM subobject AS so
INNER JOIN subrelation AS sr ON so.subId = sr.ID;

See it in action here:

  • SQL Fiddle Demo

Also, see the following post for more info about the different types of JOINs:

  • A Visual Explanation of SQL Joins.
like image 63
Mahmoud Gamal Avatar answered Oct 17 '22 08:10

Mahmoud Gamal