2

我有两个名为的表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

4 回答 4

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 子查询。使用正确的索引和外键定义,性能应该很棒。

于 2013-11-14T20:19:27.950 回答
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
于 2013-11-14T20:16:51.357 回答
1

你可以这样想

SQL小提琴

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'

结果

| ID | SUBJECT |
|----|---------|
|  1 |  hello1 |
于 2013-11-14T20:23:20.570 回答
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')
)
于 2013-11-14T20:05:14.457 回答