select count()具有两个相同的条件

jaql4c8m  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(301)

我有以下数据库。每次对话都有两个参与者。当participant.participant\u id=participantid1和participant.participant\u id=participantid2时,我想计算会话\u id的数目。

CREATE TABLE IF NOT EXISTS `users` (
    `user_id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `user_name` VARCHAR(16)
);

CREATE TABLE IF NOT EXISTS `conversation` (
    `conversation_id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `user_id` BIGINT UNSIGNED,
    `time_started` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `time_closed` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(user_id)
);

CREATE TABLE IF NOT EXISTS `participant` (
    `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `conversation_id` BIGINT UNSIGNED,
    `participant_id` BIGINT UNSIGNED,
    `time_joined` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `time_left` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (conversation_id) REFERENCES conversation(conversation_id),
    FOREIGN KEY (participant_id) REFERENCES users(user_id)
);

我尝试了类似的方法,但结果是count=0:

SELECT count(conversation.conversation_id)
FROM `conversation`
INNER JOIN `participant` on participant.conversation_id = conversation.conversation_id
WHERE participant.participant_id = ? AND participant.participant_id = ?

我设法做了不同的,但我想知道是否有可能在一个单一的查询。谢谢你的帮助!:-)

b91juud3

b91juud31#

我现在无法检查,但类似的方法应该可以:

SELECT count(c.conversation_id)
FROM conversation c
INNER JOIN participant p1 ON p1.conversation_id = c.conversation_id
INNER JOIN participant p2 ON p2.conversation_id = c.conversation_id
WHERE p1.participant_id = ? AND p2.participant_id = ?

相关问题