我有以下数据库。每次对话都有两名参与者。我要计算的是session.id.participant_id =参与者ID1和参与者.participant_id =参与者ID2时的session_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)
);
我尝试了类似的方法,但最终计数为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 = ?
我设法以不同的方式进行操作,但是我想知道是否可以在一个查询中进行操作。谢谢你的帮助! :-)
答案 0 :(得分:1)
我目前无法检查,但是这样的方法应该可以工作:
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 = ?