Jump to content

sql query for multiple tables via a linking table


scarhand

Recommended Posts

i need some help with this sql query

 

heres my mysql table structure:

 

DOMAINS

- id

- domain_name

 

KEYWORDS

- id

- keyword

- keyword_slug

 

PAGES

- id

- id_domain

- id_keyword

 

what i need is my sql query to give me results in this format:

 

- domain_name

-- keyword in domain linked via the "pages" table

-- keyword in domain linked via the "pages" table

-- keyword in domain linked via the "pages" table

- domain_name

-- keyword in domain linked via the "pages" table

-- keyword in domain linked via the "pages" table

-- keyword in domain linked via the "pages" table

 

so i was thinking something like this? not sure how to get the grouping, confusing me a little:

 

$sql = mysql_query("select d.domain_name, k.keyword from domains as d, keywords as k, pages as p where d.id=p.id_domain and k.id=p.id_keyword group by p.id_domain");

 

isn't exactly working....any help would be much appreciated.

 

Link to comment
Share on other sites

This should do what you want:

 

select d.domain_name, k.keyword
from domains as d, keywords as k, pages as p
where d.id=p.id_domain and k.id=p.id_keyword
order by p.id_domain

 

The only difference from yours is order by instead of group by. It won't be exactly the format you described, but it should be easy to write some php that works with these results. They'll look like:

 

- domain name, keyword in domain

- domain name, keyword in domain

- domain name, keyword in domain

- domain name, keyword in domain

- domain name, keyword in domain

 

Because of the order by clause though, all the records for a given domain id will be grouped together in your result set, which is (mostly) what you wanted.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.