在特定列上连接两个SQL查询结果

时间:2019-07-29 08:54:19

标签: mysql sql

我有两个很好的查询。除了一列“ client_id”外,它们具有不同的列(不同的名称)。 我想在“ client_id”列上加入这两个查询。 我已经尝试过使用unionjoin,但是它不起作用。 我究竟做错了什么?

   (SELECT i_data.client_id, 
           SUM(i_data.like_by_post) AS total_likes, 
           SUM(i_data.comment_by_post) AS total_comments
      FROM instagram_data AS i_data
  GROUP BY i_data.client_id)
INNER JOIN  
   (SELECT ig_profile.client_id, ig_profile.username, 
           ig_profile.counts_media AS total_posts, 
           ig_profile.followed_by AS followers
      FROM instagram_profile AS ig_profile
  GROUP BY ig_profile.client_id
  ORDER BY ig_profile.current_date) 
        ON i_data.client_id = ig_profile.client_id

4 个答案:

答案 0 :(得分:1)

如果要加入:

select * from (
  select i_data.client_id, sum(i_data.like_by_post) as total_likes, 
    sum(i_data.comment_by_post) as total_comments
  from instagram_data as i_data
  group by i_data.client_id
) d inner join (
  select ig_profile.client_id, ig_profile.username, 
    ig_profile.counts_media as total_posts, ig_profile.followed_by as followers
  from instagram_profile as ig_profile
  group by ig_profile.client_id
  order by ig_profile.current_date
) p
on d.client_id = p.client_id

用要选择的列替换*。
同样,第二个查询中的order by子句也没有用,您可以将其删除。您必须根据需要对结果进行排序。
由于这两个查询返回的列数不相同(数据类型相同),因此不能使用UNION。

答案 1 :(得分:0)

您的查询不正确。

请尝试以下查询:

JavaScript is either disabled in or not supported by the Web browser.
To continue logon, use a Web browser that supports JavaScript or enable JavaScript in your current browser.

答案 2 :(得分:0)

请为这两个查询指定别名,然后将它们加入代码中;

Python pyinstaller.py --onefile pythonfile.py

答案 3 :(得分:0)

select i_data.client_id, sum(i_data.like_by_post) as total_likes, sum(i_data.comment_by_post) as total_comments, 
ig_profile.client_id, ig_profile.username, ig_profile.counts_media as total_posts, ig_profile.followed_by as followers

from instagram_data as i_data
left join instagram_profile as ig_profile on i_data.client_id = ig_profile.client_id

group by ig_profile.client_id,  i_data.client_id
order by ig_profile.current_date

您可以根据需要恢复为内部联接。