简体   繁体   English

内部联接SQL语法

[英]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. 我以前从未做过内部连接SQL语句,所以我什至不知道这是否适合使用,但这是我的情况。

Table 1 Columns: id, course_id, unit, lesson Table 2 Columns: id, course_id 表1列:id,course_id,单元,课程表2列: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 . 最后,我要算的数id's各单位在表1 中也列于表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? 有修复的想法吗?

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. 希望这可以帮助。

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

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 您可能应该切换到显式编写inner join

Now, whenever you have any sort of join, you also need on . 现在,只要你有任何形式的参与,还需要on You need to tell sql how it should match these two tables up. 您需要告诉sql如何将这两个表匹配起来。 The on should come right after the join, like this: on应该在加入后立即出现,如下所示:

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 . 您可以使用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. 这是微妙的,但是sql查询不能使用额外的逗号运行。

Another issue is with the COUNT( id ) that you have. 另一个问题是您拥有的COUNT( id ) Sql doesn't know which id to count since table1 and table2 both have ids. sql不知道要计数哪个id,因为table1和table2都有ID。 So, you should use either count(table1.id) or count(table2.id) 因此,您应该使用count(table1.id)count(table2.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM