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 > sql query question

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 06-01-09, 16:49
vahidreza vahidreza is offline
Registered User
 
Join Date: Jun 2009
Posts: 9
Question sql query question

Hi , to describe what i am looking for , please take a look to these 3 tables :

groups
=========
g_id,g_name

articles
=========
a_id,a_name

rels
=========
r_id,g_id,a_id

now i need a query to return :
g_name - a_name

if there is no article for any group, then a_name would be null

i tried select from groups and rels tables, but my result set doesn't contain groups that have no articles in rels table !

any idea ?
Reply With Quote
  #2 (permalink)  
Old 06-01-09, 19:37
gvee gvee is offline
www.gvee.co.uk
 
Join Date: Jan 2007
Location: UK
Posts: 10,156
First off, the rels table doesn't need r_id - a composite key of g_id and a_id will suffice

Ok, so you want to know all groups that have no articles assigned, right?
Code:
SELECT groups.g_id
     , groups.g_name
FROM   groups
 LEFT
  JOIN rels
    ON rels.g_id = groups.g_id
WHERE  rels.g_id IS NULL
__________________
George
Twitter | Blog
Reply With Quote
  #3 (permalink)  
Old 06-02-09, 02:11
vahidreza vahidreza is offline
Registered User
 
Join Date: Jun 2009
Posts: 9
Hi,

thanx gvee for you answer but i think i couldn't make my question clear :
the result i want is a select for columns g_name And a_name between these tables.

like this :
select g_name,a_name from rels r left join groups g on g.g_id = r.g_id left join articles a on a.a_id = r.a_id

the problem in this sql query is : it doesn't return groups that have no articles
, i need such query to return all groups while there is no article !
Reply With Quote
  #4 (permalink)  
Old 06-02-09, 07:21
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
Code:
SELECT g_name
     , a_name 
  FROM groups AS g
LEFT OUTER
  JOIN rels AS r 
    ON r.g_id = g.g_id 
LEFT OUTER
  JOIN articles AS a 
    ON a.a_id = r.a_id
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #5 (permalink)  
Old 06-03-09, 02:37
vahidreza vahidreza is offline
Registered User
 
Join Date: Jun 2009
Posts: 9
thanx, it seems to work .
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