mysql子查询不会产生所有结果

时间:2014-10-11 00:10:59

标签: mysql

我有两个表:contacts和client_profiles。联系人有许多client_profiles,其中client_profiles具有外键contact_id:

联系人:

mysql> SELECT id,first_name, last_name FROM contacts;
+----+-------------+-----------+
| id | first_name  | last_name |
+----+-------------+-----------+
| 10 | THERESA     | CAMPBELL  |
| 11 | donato      | vig       |
| 12 | fdgfdgf     | gfdgfd    |
| 13 | some random | contact   |
+----+-------------+-----------+
4 rows in set (0.00 sec)

client_profiles:

mysql> SELECT id, contact_id, created_at FROM client_profiles;
+----+------------+---------------------+
| id | contact_id | created_at          |
+----+------------+---------------------+
|  6 |         10 | 2014-10-09 17:17:43 |
|  7 |         10 | 2014-10-10 11:38:01 |
|  8 |         10 | 2014-10-10 12:20:41 |
|  9 |         10 | 2014-10-10 12:24:19 |
| 11 |         12 | 2014-10-10 12:35:32 |
+----+------------+---------------------+

我想为每个联系人获取最新的client_profiles。这意味着应该有两个结果。我想使用子查询来实现这一点。这是我提出的子查询:

SELECT `client_profiles`.* 
FROM `client_profiles` 
INNER JOIN `contacts` 
ON `contacts`.`id` = `client_profiles`.`contact_id` 
WHERE (client_profiles.id = 
(SELECT  `client_profiles`.`id` FROM `client_profiles`   ORDER BY created_at desc LIMIT 1))

但是,这只会返回一个结果。它应该返回id为9和11的client_profiles。

我的子查询有什么问题?

3 个答案:

答案 0 :(得分:1)

看起来你试图在client_profile表上过滤两次,一次在JOIN / ON子句中,另一次在WHERE子句中。

移动where子句中的所有内容如下所示:

SELECT `cp`.* 
FROM `contacts` 
    JOIN (
        SELECT 
            `client_profiles`.`id`,
            `client_profiles`.`contact_id`,
            `client_profiles`.`created_at`
        FROM `client_profiles`   
        ORDER BY created_at DESC 
        LIMIT 1
    ) cp ON `contacts`.`id` = `cp`.`contact_id` 

告诉我你的想法。

答案 1 :(得分:0)

应该是这样的事情:

SELECT * 
FROM `client_profiles` 
INNER JOIN `contacts` 
ON `contacts`.`id` = `client_profiles`.`contact_id` 
GROUP BY `client_profiles`.`contact_id` 
ORDER BY created_at desc;

http://sqlfiddle.com/#!2/a3f21b/9

答案 2 :(得分:0)

您需要预先查询按联系人分组的客户端配置文件表。从中,重新加入客户端以获取此人,然后再根据相同的联系人ID再次访问客户端配置文件表,同时还匹配最大日期来自使用max(created_at)

的内部预查询
SELECT
      c.id,
      c.first_name,
      c.last_name,
      IDByMaxDate.maxCreate,
      cp.id as clientProfileID
   from 
      ( select contact_id,
               MAX( created_at ) maxCreate
            from 
               client_profiles
            group by
               contact_id ) IDByMaxDate
      JOIN contacts c
         ON IDByMaxDate.contact_id = c.id
      JOIN client_profiles cp
         ON IDByMaxDate.contact_id = cp.contact_id
         AND IDByMaxDate.maxCreate = cp.created_at