views:

420

answers:

3

I have 3 tables (archive has many sections, section (may) belong to many archives):

  • archive

    • id PK
    • description
  • archive_to_section

    • archive_id PK FK
    • section_id PK FK
  • section

    • id PK
    • description

What would the SQL look like to list all the sections that belong a certain archive id?

I am just learning SQL. From what I've read it sounds like I would need a join, or union? FYI I'm using postgres.


[Edit] This is the answer from gdean2323 written without aliases:

SELECT section.* 
FROM section 
INNER JOIN archive_to_section 
ON section.id = archive_to_section.section_id 
WHERE archive_to_section.archive_id = $this_archive_id
+3  A: 
SELECT s.*
FROM archive_to_section ats
  INNER JOIN section s ON s.id=ats.section_id
WHERE ats.archive_id= @archiveID
Joel Coehoorn
Exactly. The important thing to realize is that the archive table don't figure into this.
James Curran
beat me by 3 seconds!
Greg Dean
I think you mean INNER JOIN section s ON s.id=ats.section_id
Greg Dean
what do the * and @ symbols mean?
meleyal
* means all the fields for that table, @archiveID is a parameter, you can replace it with the archive_id of your choice, if you like.
Greg Dean
Thanks, dean. Corrected.
Joel Coehoorn
+3  A: 
SELECT s.* 
FROM section s INNER JOIN archive_to_section ats ON s.id = ats.section_id 
WHERE ats.archive_id = 1
Greg Dean
is it necessary to write with the abbreviations? it might be easier to follow for a beginner. thanks
meleyal
It is not required to use abbreviations (alias's) many people use them. I prefer not to. See the discussion on the pros/cons of alias's http://stackoverflow.com/questions/198196/when-to-use-sql-table-alias
Nathan Koop
A: 

Create a new table that contains the category code and description for the categoriesof books sold by JustLee books

Anita