SQL限制&订购跨联接

时间:2014-04-24 13:36:50

标签: mysql sql join

我存储推文,推特用户,并将Twitter用户分组。

我有以下4个表

鸣叫:

tweet_id | user_id | created
-------------------------------
23452345 | 2345    | 2013-08-12
23456094 | 1234    | 2014-03-24
23097777 | 1234    | 2014-04-12
23948798 | 9999    | 2013-09-22

twitter_users:

user_id | screen_name
------------------------
2345    | michael
1234    | david
9999    | not_interested

twitter_social:

user_id | social_id
---------------------------
2345    | 34
9999    | 20
1234    | 80

social_categories:

social_id | category_id
-----------------------
34        | 3
20        | 6
80        | 3

我希望看到每个用户出现在某个社交类别中的最早的推文。 我写的以下SQL似乎不起作用。我每twitter_user有一行,但我没有看到最早的推文

SELECT tu.screen_name as Handle, tw.created_at as Earliest
FROM twitter_users tu
    LEFT JOIN tweets tw
        ON tu.user_id = tw.user_id
    LEFT JOIN twitter_social ts
        ON ts.user_id = tu.user_id
    LEFT JOIN social_categories cs
        ON ts.social_id = cs.social_id
WHERE cs.category_id=3
GROUP BY Handle
ORDER BY Earliest ASC

修改 我希望得到如下结果

Handle  | Earliest
---------------------
david   | 2014-03-24
michael | 2013-08-12

4 个答案:

答案 0 :(得分:2)

SELECT tu.screen_name as Handle
    ,MIN(tw.created_at) as Earliest
FROM twitter_users tu
LEFT JOIN tweets tw
    ON tu.user_id = tw.user_id
LEFT JOIN twitter_social ts
    ON ts.user_id = tu.user_id
LEFT JOIN social_categories cs
    ON ts.social_id = cs.social_id
WHERE cs.category_id=3
GROUP BY tu.screen_name
ORDER BY Earliest ASC

答案 1 :(得分:1)

如果你想要最早的,那就不是ASC(升序)

ORDER BY Earliest ASC

它应该是DESC(降序)

ORDER BY Earliest DESC

答案 2 :(得分:0)

SELECT tu.screen_name as Handle, tw.created_at as Earliest
FROM twitter_users tu
LEFT JOIN tweets tw
    ON tu.user_id = tw.user_id
LEFT JOIN twitter_social ts
    ON ts.user_id = tu.user_id
LEFT JOIN social_categories cs
    ON ts.social_id = cs.social_id
WHERE cs.category_id=3
GROUP BY Handle
ORDER BY Earliest DESC
LIMIT 1

答案 3 :(得分:0)

试试这个

SELECT tu.screen_name as Handle, min(tw.created_at) as Earliest
FROM twitter_users tu
    LEFT JOIN tweets tw
        ON tu.user_id = tw.user_id
    LEFT JOIN twitter_social ts
        ON ts.user_id = tu.user_id
    LEFT JOIN social_categories cs
        ON ts.social_id = cs.social_id
WHERE cs.category_id=3
GROUP BY tu.screen_name
ORDER BY Earliest ASC