如何在 mysql 中两次加入同一个表?

我有2个表。一个(域)有域 ID,和域名(dom _ id,dom _ url)。

另一个包含实际数据,其中2列需要 TO 和 FROM 域名。因此,我有两列 rev _ dom _ from 和 rev _ dom _ for,它们都存储域名表中的域名 id。

很简单。

现在我需要在网页上实际显示两个域名。我知道如何通过 LEFT JOIN 域 ON reviews.rev _ dom _ for = domains.dom _ url 查询来显示其中之一,然后回显 dom _ url,这将回显 rev _ dom _ for 列中的域名。

但是如何让它在 dom _ rev _ from 列中回显第2个域名呢?

126976 次浏览

你可以使用另一个连接,大致如下:

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

编辑:

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).

此时,将 Domain 表留给 Reviews 表是一件简单的事情。FOR 使用一次(别名为 toD) ,FROM 使用第二次(别名为 FROM D)。

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.

有关 SQL 中别名的更多信息,请阅读 给你

根据以下表格。

Domain Table
dom_id | dom_url


Review Table
rev_id | rev_dom_from | rev_dom_for

试试这个 sql... (这和 Stephen Wrighton 上面写的差不多) 诀窍在于,您基本上是在同一个查询中从域表中选择两次并连接结果。

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.

读读这个,试试看,这会帮助你:

表一

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是与 table1.column11=table2asnew1.column21匹配的表2的一个实例

还有

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