user1421855
user1421855

Reputation: 1

mysql Inner join with different table

thanks all of you :) i have 4 table Project, points, steps, and comments;

Project id name desc

points id name desc project_id

steps id desc points_id

comments id desc steps_id

i wrote query like this

SELECT * FROM Project 
INNER JOIN points ON points.project_id=Project.id
INNER JOIN steps ON steps.points_id=points.id
INNER JOIN comments ON comments.steps_id=steps.id
WHERE Project.id=333

one project has many points, points, has many steps, and it has many comments somthing like this, and i whant to get all results in one query otherwise it takes a lot of time get results :(( i have no idea what can i do to :((

it is like this

**Project**
id :1,
name :"get",

**points**
id :1,
name :"points1", ///project "get"'s point
project_id : 1,
id :2,
name :"points2", ///project "get"'s point
project_id : 1,

**steps**
id :1,
name :"steps1", ///project "points2"'s step
points_id : 2,
id :2,
name :"steps2",///project "points2"'s step
points_id : 2,

**comments**
id :1,
name :"something", ///project "steps1"'s comment
steps_id : 1,
id :2,
name :"something",///project "steps2"'s comment
steps_id : 2,

i want to echo project, it's point, point's step and step's comments in one query or if there are another way to solve this problem? thanks for supporting :))))))

Upvotes: 0

Views: 324

Answers (4)

Rahul
Rahul

Reputation: 77866

Few thing missing in your posted query:

  1. Missing FROM clause
  2. Also, every join is not correct like table2.table1_id= table1.id ... it should be table2.table2_id= table1.id (Unless your table design is like so)

So, ultimately your query should look like

SELECT *  FROM Table1        
INNER JOIN table2 ON table2.table2_id= table1.id        
INNER JOIN table3 ON table3.table2_id= table1.id        
INNER JOIN table4 ON table4.table4_id= table1.id 
WHERE table1.ID = 333 

Upvotes: 1

John Woo
John Woo

Reputation: 263703

First of all, you have an invalid sql syntax. You missed the keyword FROM. It should be:

SELECT * 
FROM Table1
       INNER JOIN table2 ON table2.table1_id= table1.id
       INNER JOIN table3 ON table3.table2_id= table2.id
       INNER JOIN table4 ON table4.table3_id= table3.id
WHERE table1.ID = 333

But I need your desired result. You need to specify your database schema and dummy records to complete your query.

Upvotes: 2

user928558
user928558

Reputation:

There is a typo in the last INNER JOIN. table2 should be table4.

Upvotes: 0

Ras
Ras

Reputation: 628

You're currently retrieving all columns from Table1 by filtering the ID with value 333. What about further columns from other tables? what kind of resut you're expecting?

Upvotes: 0

Related Questions