1

我在创建查询时遇到了小麻烦。我有两张桌子:

user_data
+----+---------+--------+
| id | mail    | etc... |
+----+---------+--------+
|  1 | 1@m.com | ...    |
|  2 | 2@m.com | ...    |
|  3 | 3@m.com | ...    |
+----+---------+--------+

 

contracts
+----+---------+--------+
| id | user_id | etc... |
+----+---------+--------+
|  1 |       1 | ...    |
|  2 |       2 | ...    |
|  3 |       1 | ...    |
|  4 |       1 | ...    |
|  5 |       3 | ...    |
+----+---------+--------+

如您所见,第一个表包含有关用户的数据,第二个表包含有关其合同的数据。关于一个用户的条目总是只有一个,但一个用户可以有多个合同。现在我需要找出所有用户,他们的第一个合同 id (合同表中的最低 id)和他们的电子邮件,如果它在 are 参数中。

到目前为止,我有这样的查询:

SELECT
  u.id as user_id,
  c.id as first_contract_id,
  u.mail as email
FROM
  user_data u
JOIN
  contracts c ON u.id = c.user_id
WHERE
  u.mail
IN (
  '1@me.com',
  '2@me.com',
  '3@me.com'
);

现在我不知道如何only the lowest contract ID从这些结果中进行选择。帮助赞赏。

4

2 回答 2

1
select 
    u.id as user_id, 
    c.id as first_contract_id, 
    u.Mail as email 
from users as u inner join
(
    select min(id) as id,user_id from contracts 
    group by user_id
) as c
on  u.id = c.user_id 
WHERE 
      u.mail 
    IN ( 
      '1@me.com', 
      '2@me.com', 
      '3@me.com' 
    ); 
于 2012-07-27T13:37:42.383 回答
1
SELECT
  u.id as user_id,
  min(c.id) as first_contract_id,
  u.Mail as email
FROM
  user_data u
JOIN
  contracts c ON u.id = c.user_id
WHERE
  u.mail IN ('1@me.com', '2@me.com', '3@me.com')
GROUP BY u.id

如果您group by是用户,您可以使用min.

(并且MySQL选择不在组中的列没有问题)

于 2012-07-27T13:35:40.513 回答