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

后端 未结 3 1492
面向向阳花
面向向阳花 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: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.

提交回复
热议问题