If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Help with complex inner join

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 11-15-09, 11:36
mrcs mrcs is offline
Registered User
 
Join Date: Nov 2009
Posts: 2
Question Help with complex inner join

Hi, members,

I'm working on simple forum and I can't make one query.

I want to show on homepage list of topics where will be the author of the topic and author of last post.

I can make any of them but not together, because there is double inner join to one table (one for topic author and second for last post's author).

Tables (just with necesary parts):

Topics
######
id
author_id (will be connected directly to Users.id)
last_post_id (will be connected to Posts.id)

Posts
#####
id
author_id (connected to Users.id)

Users
#####
id
name

I can start with this and I don't know how to continue:
Code:
SELECT topics.author_id, topics.last_post_id, users.name, 
FROM topics
INNER JOIN users ON topics.author_id = users.id
It will give back topic's names, their authors and ID of last post. And I want to know last post's author's name.

Can anyone help, please?

Thanks for any response
Reply With Quote
  #2 (permalink)  
Old 11-15-09, 14:45
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
Code:
SELECT topicauthor.name AS topic_author_name
     , lastposter.name AS last_poster_authr_name
  FROM topics
INNER 
  JOIN users AS topicauthor 
    ON topicauthor.id = topics.author_id
INNER
  JOIN posts
    ON posts.id = topics.last_post_id
INNER
  JOIN users as lastposter
    ON lastposter.id = posts.author_id
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 11-15-09, 14:52
mrcs mrcs is offline
Registered User
 
Join Date: Nov 2009
Posts: 2
You're just genius, man! Tahnks a lot

I haven't heard about "table alias" in Inner join. Thanks for fast help!
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On