SQLite:循环SELECT语句,替换WHERE子句

时间:2014-05-05 23:41:20

标签: sqlite loops

我有以下两个表:

CREATE TABLE messages (
  id integer UNIQUE NOT NULL,
  message text,
  recipient integer NOT NULL,
  sender integer NOT NULL,
  sent_at text NOT NULL,
  FOREIGN KEY (recipient) REFERENCES users (id),
  FOREIGN KEY (sender) REFERENCES users (id)
);
CREATE TABLE users (
  id integer UNIQUE NOT NULL,
  username text NOT NULL,
);

我需要一个非常具体的查询,如下所示:

SELECT *
FROM messages
WHERE sender = 123 OR recipient = 123
ORDER BY id desc
LIMIT 1

我需要对消息表进行迭代,使用每个用户,并将他置于WHERE语句中。

-- TABLE 'users':
-- 123 = id of user1
-- 456 = id of user2
-- 789 = id of user3

是否可以在SQLite中进行迭代?

目标是,为users表中的每个用户获取最新的“对话”。对于每个用户,无论他发送或接收到最新消息,都应显示涉及他的最新消息。

2 个答案:

答案 0 :(得分:1)

您可以使用相关子查询为每个用户ID获取该值:

SELECT id,
       username,
       (SELECT MAX(id)
        FROM messages
        WHERE sender    = users.id
           OR recipient = users.id
       ) AS last_message_id
FROM users

GROUP BY也可以这样做。 首先将两个表连接在一起,然后为每个用户创建一个组:

SELECT users.id,
       MAX(messages.id)
FROM users
JOIN messages ON users.id = messages.sender OR
                 users.id = messages.recipient
GROUP BY users.id

答案 1 :(得分:0)

SELECT year , COUNT(*) AS Count 
FROM Movie
WHERE Movie.MID NOT IN
       (SELECT DISTINCT m.MID 
         FROM Movie m 
         JOIN M_Cast m_c ON m.MID = m_c.MID 
         JOIN Person p_1 ON m_c.PID = p_1.PID  
         AND p_1.Gender='Male')
AND Movie.MID IN
       (SELECT DISTINCT m.MID 
         FROM Movie m 
         JOIN M_Cast m_c ON m.MID = m_c.MID 
         JOIN Person p_1 ON m_c.PID = p_1.PID 
         AND p_1.Gender='Female')
GROUP BY year;