gtilflm
gtilflm

Reputation: 1465

Inner Join SQL Syntax

I've never done an inner join SQL statement before, so I don't even know if this is the right thing to use, but here's my situation.

Table 1 Columns: id, course_id, unit, lesson Table 2 Columns: id, course_id

Ultimately, I want to count the number of id's in each unit in Table 1 that are also in Table 2.

So, even though it doesn't work, maybe something like....

$sql = "SELECT table1.unit, COUNT( id ) as count, table2.id, FROM table1, table2, WHERE course_id=$im_course_id GROUP BY unit";

I'm sure the syntax of what I'm wanting to do is a complete fail. Any ideas on fixing it?

Upvotes: 0

Views: 162

Answers (3)

Jenn
Jenn

Reputation: 795

Okay, so there are a few things going on here. First off, commas as joins are deprecated so they may not even be supported (depending on what you are using). You should probably switch to explicitly writing inner join

Now, whenever you have any sort of join, you also need on. You need to tell sql how it should match these two tables up. The on should come right after the join, like this:

Select *
From    table1 inner join table2
    on table1.id = table2.id
    and table1.name = table2.name

You can join on as many things as you need by using and. This means that if the primary key of one table is several columns, you can easily create a one-to-one match between tables.

Lastly, you may be having issues because of other general syntax errors in your query. A comma is used to separate different pieces of information. So in your query,

SELECT table1.unit, COUNT( id ) as count, table2.id, FROM ...

The comma at the end of the select shouldn't be there. Instead this should read

SELECT table1.unit, COUNT( id ) as count, table2.id FROM ...

This is subtle, but the sql query cannot run with the extra comma.

Another issue is with the COUNT( id ) that you have. Sql doesn't know which id to count since table1 and table2 both have ids. So, you should use either count(table1.id) or count(table2.id)

Upvotes: 0

Pupa Rebbe
Pupa Rebbe

Reputation: 528

SELECT unit, COUNT( t1.id ) as count
FROM table1 as t1 inner JOIN table2 as t2 
  ON t1.id = t2.id
GROUP BY unit

hope this helps.

Upvotes: 1

Jonny
Jonny

Reputation: 2519

If I understand what you want (maybe you could post an example input and output?):

SELECT unit, COUNT( id ) as count
FROM table1 as t1 JOIN table2 as t2 
  ON t1.id = t2.id
GROUP BY unit

Upvotes: 0

Related Questions