2012-03-20 84 views
0

我有兩個表,用戶和hra。用戶在用戶表中只能有一條記錄,但他可以有多個記錄。我想要做的只是每個用戶檢索一個hra。我有下面的查詢。任何人都可以幫忙做到這一點?如何爲每個用戶選擇一條記錄?

$query = "SELECT u.id AS user_id, h.id AS hra_id FROM users u 
      INNER JOIN hra h ON u.id = h.user_id 
      WHERE h.date BETWEEN ? AND ? 
      AND h.done = 1 
+0

你想要哪HRA?你爲什麼只想要一個? – Yamikuronue 2012-03-20 15:16:11

+1

是否存在您想要檢索的特定'hra',或者您對符合您的'WHERE'子句的任何'hra'滿意嗎? – ruakh 2012-03-20 15:16:22

回答

2

假設你想要的MAX(h.id),這應該工作:

SELECT u.id AS user_id, MAX(h.id) AS hra_id FROM users u 
     INNER JOIN hra h ON u.id = h.user_id 
     WHERE h.date BETWEEN ? AND ? 
     AND h.done = 1 
GROUP BY u.id 
相關問題