考虑第二个表中的两个记录,连接表(1:n)

时间:2013-11-14 19:54:57

标签: mysql

我有两个名为letterletter_person的表,如下所示:

letter

id | subject | body | time
==========================
 1 |  Hello  | null | ...
 .
 .
 .

letter_person

id | ref_person | ref_letter |   role
========================================
 1 |     1      |     1      |   sender
 2 |     2      |     1      |  receiver
 .
 .
 .

role是一个枚举字段,可以是senderreceiver

我想选择两个人之间发送和接收的信件,我想要这样的事情:

SELECT * FROM letter
JOIN letter_person ON letter_person.ref_letter = letter
WHERE
(letter_person.ref_person = 1 AND letter_person.role = 'sender') 
OR
(letter_person.ref_person = 2 AND letter_person.role = 'receiver')

但这并不是我所需要的。

此查询选择person1发送的所有字母+ person2收到的所有字母。

我需要进行对话。

4 个答案:

答案 0 :(得分:1)

JOINletter_person表两次......一次获得发件人,一次获得接收者。这样做的好处是可以让您查看充当发件人和收件人的人员的详细信息:

SELECT
    sender.ref_person AS sender_ref_person,
    receiver.ref_person AS receiver_ref_person,
    l.id,
    l.subject,
    l.body,
    l.time
FROM
    letter l
    JOIN letter_person sender
        ON sender.ref_letter = l.id
        AND sender.role = 'sender'
    JOIN letter_person receiver
        ON receiver.ref_letter = l.id
        AND receiver.role = 'receiver'
WHERE
    sender.ref_person = 1
    AND receiver.ref_person = 2

答案 1 :(得分:1)

您可以使用以下内容:

SELECT *
FROM letter
JOIN letter_person AS sender ON letter.id = sender.ref_letter AND sender.role = 'sender'
JOIN letter_person AS receiver ON letter.id = receiver.ref_letter_id and receiver.role = 'receiver'
WHERE sender.ref_person = 1
AND receiver.ref_person = 2

归功于上一个回答指出我的遗漏! : - )

这样做的好处是不必使用IN子查询。使用适当的索引和外键定义,性能应该是非常棒的。

答案 2 :(得分:1)

你可以这样想吗

SQL Fiddle

MySQL 5.5.32架构设置

create table letter(id int, subject varchar(10));
create table letter_person(id int, ref_person int, ref_letter int, role varchar(1));

insert into letter values(1, 'hello1');
insert into letter values(2, 'hello2');

insert into letter_person values(1, 1, 1, 's');
insert into letter_person values(1, 2, 1, 'r');
insert into letter_person values(1, 3, 2, 's');
insert into letter_person values(1, 2, 2, 'r');

查询1

SELECT l.* FROM letter l
INNER JOIN letter_person lps ON l.id = lps.ref_letter AND lps.ref_person = 1 AND lps.role='s'
INNER JOIN letter_person lpr ON l.id = lpr.ref_letter AND lpr.ref_person = 2 AND lpr.role='r'

<强> Results

| ID | SUBJECT |
|----|---------|
|  1 |  hello1 |

答案 3 :(得分:0)

你可以做这样的事情

SELECT * FROM letter
JOIN letter_person ON letter_person.ref_letter = letter
WHERE 
(letter_person.ref_person = 1 AND letter_person.role = 'sender') 
AND letter_person.ref_letter in (
    SELECT letter_person.ref_letter FROM letter_person
    WHERE
    (letter_person.ref_person = 2 AND letter_person.role = 'receiver')
)