简体   繁体   English

MySQL Inner Join 2表

[英]MySQL Inner Join 2 tables

SELECT *
FROM tableA a
INNER JOIN tableB b
ON  a.someColumn = b.otherColumn
INNER JOIN tableC c
ON b.anotherColumn = c.nextColumn

What if tableA and tableB has the same name in fields? 如果tableA和tableB在字段中具有相同的名称,该怎么办? How can I use: 我该如何使用:

<?
$name = mysql_fetch...
echo $name['a.title'] . ' ' . $name['b.title'];
?>

So I could get title from tableA and title from tableB. 所以我可以从tableA获得标题,从tableB获得标题。 Because now, if use just $name['title'] it returns tableA's title. 因为现在,如果仅使用$name['title']它将返回tableA的标题。 And the above code unfortunately gives just an empty string. 不幸的是,以上代码仅给出了一个空字符串。

Instead of doing select * , you can put an alias on the columns as well. 您也可以在列上添加别名,而不是执行select *

SELECT a.title AS 'a_title', b.title AS 'b_title'
-- ...

Then your PHP would be something like: 然后你的PHP将是这样的:

$name['a_title']

Use an alias 使用别名

SELECT  a.title AS TitleA,
        b.title AS TitleB,
        ...

FROM ... 来自......

Then reference the alias: 然后引用别名:

$name['TitleA']

Stop using SELECT * ! 停止使用SELECT *

Explicitly list your columns, which will then allow you to alias them as needed. 明确列出您的列,然后允许您根据需要对它们进行别名。

SELECT a.title AS TableATitle, b.title AS TableBTitle, ...

Instead of using SELECT *, you will have to call out the fields by name. 而不是使用SELECT *,您必须按名称调出字段。 When you do this, you can assign an alias to be used for each. 执行此操作时,可以为每个分配一个别名。

SELECT a.title AS aTitle, b.title AS bTitle, etc...
SELECT *, a.title as atitle, b.title as btitle
FROM tableA a
INNER JOIN tableB b
ON  a.someColumn = b.otherColumn
INNER JOIN tableC c
ON b.anotherColumn = c.nextColumn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM