如何从连接表上的多个id中选择最低id

时间:2012-07-27 13:33:30

标签: mysql

创建查询时遇到问题。我有两张桌子:

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最低)及其电子邮件,如果它们是参数。

到目前为止,我有这样的疑问:

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。帮助apreciated。

2 个答案:

答案 0 :(得分: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选择不在组中的列没有问题)

答案 1 :(得分: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' 
    );