Mysql子查询限制或使用多个查询

时间:2012-12-05 12:02:14

标签: mysql

是否可以为每个状态选择2个问题。我知道mysql不支持子查询的限制,但我看到了解决方法,我无法弄清楚如何使用这个查询。这是一个查询问题还是我必须使用额外的查询?我正在尝试为每种状态选择2行。

如果没有LIMIT 2,以下查询将起作用,但结果太多,因此需要限制它。

SELECT id FROM questions WHERE status_id = c.status_id LIMIT 2

查询:

  ...
    FROM questions q, users u, users lu, tags t, question_tags tt, connection c
   WHERE q.user_id = u.id
     AND tt.tag_id = t.id
     AND tt.question_id = q.id
     AND c.user_id = 100
     AND q.last_user = lu.id
     AND q.id IN (SELECT id FROM questions WHERE status_id = c.status_id LIMIT 2)
GROUP BY q.id
ORDER BY q.date DESC

1 个答案:

答案 0 :(得分:0)

...
    FROM questions q, users u, users lu, tags t, question_tags tt, connection c
   WHERE q.user_id = u.id
     AND tt.tag_id = t.id
     AND tt.question_id = q.id
     AND c.user_id = 100
     AND q.last_user = lu.id
     AND q.id IN (SELECT MAX(id) FROM questions WHERE status_id = c.status_id, 
                  SELECT MAX(id) FROM questions WHERE status_id = c.status_id AND id < 
                        (SELECT MAX(id) FROM questions WHERE status_id = c.status_id))
GROUP BY q.id
ORDER BY q.date DESC

丑陋,我知道,但它应该有用。