我需要检索两个用户之间的谈话,但我不知道如何...我的结果有不必要的谈话,我当前的SQL:
select *
from user_talk t1
inner join user_talk t2 on t2.id = t1.id
where
t1.talk_id = t2.talk_id and
(
t1.user_id = 1 or
t2.user_id = 4
);
此sql显示用户1和4之间的结果,但用户1和用户2以及用户2和65之间也是如此,但我只想要用户1和4。
如何编写正确的sql?
编辑:user_talks
CREATE TABLE IF NOT EXISTS `reverse`.`user_talk` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`talk_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
`type` VARCHAR(10) NOT NULL DEFAULT 'INVITED',
`status` VARCHAR(10) NOT NULL DEFAULT 'ACTIVE',
`created_at` TIMESTAMP NULL,
`updated_at` TIMESTAMP NULL,
PRIMARY KEY (`id`),
INDEX `fk_usertalk_1_idx` (`user_id` ASC),
INDEX `fk_usertalk_2_idx` (`talk_id` ASC),
INDEX `user_in_talk_idx` (`talk_id` ASC, `user_id` ASC),
CONSTRAINT `fk_usertalk_1`
FOREIGN KEY (`user_id`)
REFERENCES `reverse`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_usertalk_2`
FOREIGN KEY (`talk_id`)
REFERENCES `reverse`.`talk` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
通话
CREATE TABLE IF NOT EXISTS `reverse`.`talk` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`created_at` TIMESTAMP NULL,
`updated_at` TIMESTAMP NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
消息
CREATE TABLE IF NOT EXISTS `reverse`.`message` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`talk_id` INT(10) UNSIGNED NOT NULL,
`sender_id` INT(10) UNSIGNED NOT NULL,
`receiver_id` INT(10) UNSIGNED NOT NULL,
`body` TEXT NOT NULL,
`status` VARCHAR(10) NOT NULL DEFAULT 'UNREAD',
`created_at` TIMESTAMP NULL,
`updated_at` TIMESTAMP NULL,
PRIMARY KEY (`id`),
INDEX `fk_message_1_idx` (`sender_id` ASC),
INDEX `fk_message_2_idx` (`receiver_id` ASC),
INDEX `fk_message_3_idx` (`talk_id` ASC),
CONSTRAINT `fk_message_1`
FOREIGN KEY (`sender_id`)
REFERENCES `reverse`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_message_2`
FOREIGN KEY (`receiver_id`)
REFERENCES `reverse`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_message_3`
FOREIGN KEY (`talk_id`)
REFERENCES `reverse`.`talk` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
答案 0 :(得分:1)
从用户1到用户4以及从用户4到用户1选择user_talks:
SELECT *
FROM user_talk t1
INNER JOIN user_talk t2 ON t1.talk_id = t2.talk_id
WHERE
(t1.user_id = 1 AND t2.user_id = 4)
OR
(t1.user_id = 4 AND t2.user_id = 1)
我解释说:
答案 1 :(得分:0)
(请试试这个
select *
from user_talk t1
inner join user_talk t2 on t1.id = t2.id
where (t1.user_id = 1 or t1.user_id = 4)
and (t2.user_id = 1 or t2.user_id = 4);
更新:只为下面显示的数据运行此SQL
只有
user_id
1& 4