将许多sql表与连接相结合 - 最有效的方法

时间:2014-04-18 09:35:02

标签: mysql sql join

我有6张桌子,我想加入他们中的大多数来获得1个视图。

   fb_stats
    -------------
    -fb_Account_id # these fb account ids range from 1-8
    -num_likes
    -date

    fb_account
    -------------
    -fb_account_id 
    -fb_account_name # the name of the fb account ids (8 of them)
    -date

    twt_stats
    ------------
    -twt_Account_id # these twt account ids range from 1-11
    -num_followers 
    -date

    twt_account
    ------------
    -twt_Account_id
    -twt_account_name # these twt account_names correspond to the twt account id ranging from          
    -date               1-11

    ga_1                # this is the fb_account_name of one of the fb accounts and it has          
                          fb_Account_id=3. It is also the twt_account_name with     
                           twt_account_id=5
    -----------
    -unique_visits_1
    -date


    ga_2                 # this is the fb_account_name of one of the fb accounts and it has           
                           fb_Account_id=2. It is also the twt_account_name with          
                           twt_account_id=7
    ------------
    -unique_visits_2
    -date

Given that date is the only common factor in all 6 tables, while table ga_1 and ga_2 are subsets of accounts in the first 4 tables, how can i create a view with this fields?

New View
----------------
-date
-fb_Account_id 
-fb_Account_name
-num_likes
-num_followers
-unique_visits

因此,为了创建此表并显示字段唯一身份访问次数,我们必须显示fb_account_id 3 = twt_account_id 5 for 1 row

fb_account_id 2 = twt_account_id 7 for the next row

Example table
--------------
date      fb_account_id    fb_account_name  num_likes  num_followers  uniqueVisit
04-18-14       3                 Ga1            100           1000        600

01-01-13       10                Ga9              30            800        NULL  

我的方法是在ga1和ga2中添加一个列,其中有一个id = all 3或全部2的列,以便它可以加入到这些id上的fb_account_id或tweet_account_id。

USE `my_database`;
CREATE  OR REPLACE VIEW `total_audience` AS
Select 
date(fb_stats.date) as Date,
fb_stats.num_likes AS fb_likes,
fb_stats.fb_account_id AS fb_acct,
twt_stats.num_followers AS twt_followers,
twt.account_id AS tweet_acct
FROM
fb_stats 
Join 
twt_stats 
ON twt_stats.date=date(fb_stats.date)
  .
  .

0 个答案:

没有答案