How do you join on the same table, twice, in mysql?

后端 未结 3 1465
面向向阳花
面向向阳花 2020-11-22 10:46

I have 2 tables. One (domains) has domain ids, and domain names (dom_id, dom_url).

the other contains actual data, 2 of which columns require a TO and FROM domain na

相关标签:
3条回答
  • 2020-11-22 11:09

    Given the following tables..

    Domain Table
    dom_id | dom_url
    
    Review Table
    rev_id | rev_dom_from | rev_dom_for
    

    Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

    Select d1.dom_url, d2.dom_id from
    review r, domain d1, domain d2
    where d1.dom_id = r.rev_dom_from
    and d2.dom_id = r.rev_dom_for
    

    If you are still stuck, please be more specific with exactly it is that you don't understand.

    0 讨论(0)
  • 2020-11-22 11:14

    you'd use another join, something along these lines:

    SELECT toD.dom_url AS ToURL, 
        fromD.dom_url AS FromUrl, 
        rvw.*
    
    FROM reviews AS rvw
    
    LEFT JOIN domain AS toD 
        ON toD.Dom_ID = rvw.rev_dom_for
    
    LEFT JOIN domain AS fromD 
        ON fromD.Dom_ID = rvw.rev_dom_from
    

    EDIT:

    All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

    At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

    Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

    For more info about aliasing in SQL, read here.

    0 讨论(0)
  • 2020-11-22 11:24

    Read this and try, this will help you:

    Table1

    column11,column12,column13,column14
    

    Table2

    column21,column22,column23,column24
    
    
    SELECT table1.column11,table1.column12,table2asnew1.column21,table2asnew2.column21 
    FROM table1 INNER JOIN table2 AS table2asnew1 ON table1.column11=table2asnew1.column21  INNER TABLE table2 as table2asnew2 ON table1.column12=table2asnew2.column22
    

    table2asnew1 is an instance of table 2 which is matched by table1.column11=table2asnew1.column21

    and

    table2asnew2 is another instance of table 2 which is matched by table1.column12=table2asnew2.column22

    0 讨论(0)
提交回复
热议问题