你怎么在 mysql 中加入同一张表,两次?

本教程将介绍你如何在 mysql 中加入同一张表,两次?的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

你怎么在 mysql 中加入同一张表,两次? 教程 第1张

问题描述

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 names. So I have 2 columns rev_dom_from and rev_dom_for, both of which store the domain name id, from the domains table.

Simple.

Now I need to actually display both domain names on the webpage. I know how to display one or the other, via the LEFT JOIN domains ON reviews.rev_dom_for = domains.dom_url query, and then you echo out the dom_url, which would echo out the domain name in the rev_dom_for column.

But how would I make it echo out the 2nd domain name, in the dom_rev_from column?

解决方案

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

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.

好了关于你怎么在 mysql 中加入同一张表,两次?的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。