1

我将三个数据库表(MySQL)简化为以下信息:

===============
member
---------------
id
FirstName
===============

member.id = quote_details.member_id

===============
quote_details
---------------
member_id
insurer_id
===============

quote_details.insurer_id =insurer.id

===============
insurer
---------------
id
Name
===============

我想输出的是member.FirstNameand insurer.Name,所以我知道我需要在所有表之间连接 - 即 member > quote_details 然后 quote_details > insurance。不过,我正在为连接类型而苦苦挣扎,并希望有人能够为我指明正确的方向。

提前感谢您的任何回复。

问候,

尼尔

编辑以澄清:

我已经尝试INNER JOIN过这三个,但它返回了一个包含被查询成员名字的所有保险公司的列表:

==========================
FirstName | Insurer
--------------------------
Test      | Insurer One
Test      | Insurer Two
Test      | Insurer Three
==========================

因为我只需要分配给会员报价的实际保险公司。我希望这有助于澄清一些事情。

编辑以添加示例数据:

===================
member
-------------------
id | FirstName
- - - - - - - - - -
 1 | Test
 2 | John
 3 | Jane
===================

=======================
quote_details
-----------------------
member_id | insurer_id
- - - - - - - - - - - -
        1 |          1
=======================

===================
insurer
-------------------
id | Name
- - - - - - - - - -
 1 | Insurer One
 2 | Insurer Two
 3 | Insurer Three
===================

这希望现在可以提供所有清晰度:¬)

4

2 回答 2

0

Basically, an INNER JOIN will suffice your needs if both columns in table quote_details are non-nullable columns.

SELECT  b.FirstName MemberName,
        c.Name InsurerName
FROM    quote_details a
        INNER JOIN member b
            ON a.member_ID = b.id
        INNER JOIN insurer c
            ON a.insurer_ID = c.ID

To further gain more knowledge about joins, kindly visit the link below:

于 2013-03-20T13:28:12.467 回答
0

您的数据设置为允许会员拥有多家保险公司(反之亦然)。如果您希望所有保险公司都在同一行,则需要进行聚合:

select m.FirstName, group_concat(i.Name separator ', ') as Insurers
from member m inner join
     quote_details qd
     ON qd.member_ID = m.id inner join
     insurer i
     ON qd.insurer_ID = i.ID
group by m.FirstName

给表别名时,使用合理的缩写而不是“a”、“b”、“c”等。合理的缩写使查询更容易理解。

如果您的成员没有保险公司,他们将不会出现在输出中。如果您想要所有这些,请使用left outer join

select m.FirstName, group_concat(i.Name separator ', ') as Insurers
from member m left outer join
     quote_details qd
     ON qd.member_ID = m.id left outer join
     insurer i
     ON qd.insurer_ID = i.ID
group by m.FirstName

如果您希望它们在不同的行上:

select m.FirstName, i.Name
from quote_details qd inner join
     member m
     ON qd.member_ID = m.id inner join
     insurer i
     ON qd.insurer_ID = i.ID
于 2013-03-20T13:38:43.803 回答