在多个表上加入,提供重复记录 - MySql

时间:2017-09-06 13:42:17

标签: mysql join

这是我的表和必要列的列表

用户

screen_name,
country,
status

twitter_users_relationship tf 。对于每个target_screen_name,此表格有多个screen_name

screen_name,
target_screen_name,
target_country,
follow_status

user_twitter_action_map ta

screen_name,
action_name,
action_status

user_targeted_countries utc 。此表每个screen_name有多个国家/地区

screen_name,
country_name

我希望target_screen_nametwitter_users_relationship匹配target_countryu.country

的所有utc.country_name

到目前为止我的查询

SELECT u.screen_name,
       u.country,
       tf.target_screen_name,
       tf.target_country,
       ta.action_name,
       ta.action_status,
       utc.country_name

FROM users u
 LEFT JOIN twitter_users_relationship tf
   ON u.screen_name=tf.screen_name
 LEFT JOIN user_twitter_action_map ta
   ON u.screen_name=ta.screen_name
   AND ta.action_name='follow'
   AND ta.action_status='active'
 LEFT JOIN user_targeted_countries utc
   ON u.screen_name= utc.screen_name
WHERE u.status = 'active'
  AND tf.follow_status = 'pending'
  AND tf.target_country != ''
  AND tf.target_country IS NOT NULL
  AND ( utc.country_name=tf.target_country OR u.country=tf.target_country)
  AND u.screen_name = 'my_screen_name';

但是这个查询为我提供了user_targeted_countries中每个国家/地区条目的重复记录。如果user_targeted_countries中有3个县,则会返回3个重复记录。

请告诉我JOIN我需要使用user_targeted_countries来获得所需的结果。

u.country可能与utc.country_name

中的国家/地区不同

更新 - 如果我从OR u.country=tf.target_country子句中删除WHERE,那么我将获得所有匹配的target_screen_name,而不会重复。但我不确定如何获得与u.country=tf.target_country匹配的所有记录?

1 个答案:

答案 0 :(得分:2)

取决于所需的业务逻辑..

首先,无论问题如何,您的查询都是错误的(LEFT JOIN或条件)。使用LEFT JOIN时,右表中的条件应在ON子句中指定 ,这意味着您需要移动tf.上的所有条件和{ {1}} utc.条款。

其次,您可以使用ON子句并选择其中一个GROUP BY(如果您想要特定的答案,将会有不同的答案,如果不重要,请使用{{1}在这一栏上。)

相关问题