具有多个表的多个内部联接 [英] Multiple inner joins with multiple tables

查看:80
本文介绍了具有多个表的多个内部联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有四个桌子.每个表都有一个与前一个表ID相同的ID.因此,我的点击表中有一个ID和一个广告来源的ID.在广告表中,它有一个广告ID和一个来自其广告系列的ID.所以这是一个例子.

So I have four tables. Each table has a single id for the previous table id. So my in click table has an id and an id for the ad from which it came. In the ad table, it has an id for the ad and one for the campaign it's from. So here's an example.

Table4 -
id   company      table_id
11     hp           20
12     apple        23
13     kohls        26  
14     target       21
15     borders      28

Table3 - 
id    value    table2_id
21     ks          53
22     al          54
23     tx          53 
24     fl          55
25     co          51

Table2 -
id    value    table1_id
51     ks          34
52     al          34
53     tx          33 
54     fl          35
55     co          31

Table1 -
id    value    
31     ks        
32     al          
33     tx          
34     fl          
35     co  

因此,要找出表4中的值从何而来,我需要遍历每个表并检查它们具有哪个ID.基本上,我想知道表1中的哪些值与表4中的值相关.

So to find out where the values in Table 4 came from, I need to work back through each table and check which id they have. Basically, I want to know which values in table 1 are associated with the values in table 4.

表4中的内容是网站的访问者,表1中的内容是互联网广告.我想知道哪些访客来自哪些广告.不幸的是,这些数据是经过设置的,因此我只能从访问者到源代码再到广告组再到广告一步.这有道理吗?

This of table 4 as visitors to a website and Table 1 as internet ads. I want to know which visitors came from which ads. Unfortunately, the data is set up so that I can only take single steps back from visitor to source to ad group to ad. Does that make sense?

无论如何,我想知道是否使用4个内部联接是解决此问题的最佳策略,还是我不知道有没有一些更简单的mysql解决方案.

Anyways, I'm wondering if using 4 innner joins was the optimal strategy for this problem or is there some simpler mysql solution that i'm not aware of.

推荐答案

内部联接可能是最好的方法,您只需要3.

Inner joins are probably the best method, and you only need 3.

这将为您提供一个包含两列的结果集:公司和相关值.

This will give you a result set with two columns: company and associated values.

SELECT Table4.company, table1.id, table1.value
FROM Table1
    INNER JOIN Table2
        ON Table2.table1_id = Table1.id
    INNER JOIN Table3
        ON Table3.table2_id = Table2.id
    INNER JOIN Table4
        ON Table4.table3_id = Table3.id

这篇关于具有多个表的多个内部联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆