0

我有两张桌子

members
+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| mindex     | smallint(4) | NO   | PRI | NULL    | auto_increment | 
| memberid   | smallint(5) | YES  | MUL | NULL    |                | 
| forenames  | varchar(40) | YES  |     | NULL    |                | 
| surname    | varchar(20) | YES  |     | NULL    |                | 
| nameprefix | varchar(30) | YES  |     | NULL    |                | 
| namesuffix | varchar(50) | YES  |     | NULL    |                | 
| died       | smallint(5) | YES  |     | NULL    |                | 
| notes      | text        | YES  |     | NULL    |                | 
+------------+-------------+------+-----+---------+----------------+

memberships;
+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| mshipindex | smallint(4) | NO   | PRI | NULL    | auto_increment | 
| memberid   | smallint(5) | YES  | MUL | NULL    |                | 
| msid       | smallint(5) | YES  |     | NULL    |                | 
| mstype     | varchar(20) | YES  |     | NULL    |                | 
| msyear     | smallint(5) | YES  |     | NULL    |                | 
| msposition | varchar(15) | YES  |     | NULL    |                | 
+------------+-------------+------+-----+---------+----------------+

我想搜索一年的会员资格(在memberships.msyear)并获得memberships.mstypemembers.surname。我只是无法获得正确的 JOIN 语法。

4

2 回答 2

1

你将使用这样的东西:

select m.surname,
  s.mstype
from members m
left join memberships s
  on m.memberid = s.memberid
where s.msyear = yourYear

请参阅带有演示的 SQL Fiddle

我用 aLEFT JOIN来返回所有成员,即使是那些可能没有会员记录的人。如果成员在成员资格表中没有记录,则它将返回 null。

如果您在学习 JOIN 语法方面需要帮助,这里有一个关于连接的可视化解释

于 2012-12-12T11:32:57.390 回答
0

如果您只需要语法这里是:

Select *
from members m
inner join membership ms on (m.memberid = ms.memberid)
where memberships.msyear = 2012
于 2012-12-12T11:31:44.900 回答