2012-03-01 74 views
1
SELECT * 
FROM tableA a 
INNER JOIN tableB b 
ON a.someColumn = b.otherColumn 
INNER JOIN tableC c 
ON b.anotherColumn = c.nextColumn 

如果tableA和tableB在字段中具有相同的名称会怎样?我如何使用:MySQL内部联接2个表

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

所以我可以从tableA和titleB从tableB得到标题。因为现在,如果仅使用$name['title'],它将返回tableA的标题。上面的代码不幸的只是一个空字符串。

+0

这可能会帮助你的名字你想要的列,而不是使用'*'。 – 2012-03-01 19:13:45

回答

3

而不是做select *,你也可以在列上放置一个别名。

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

那么你的PHP将是这样的:

$name['a_title'] 
+0

38秒,没有橙色的警告栏。 Drats! ; p – 2012-03-01 19:14:38

+0

可能值得解释*为什么*不使用SELECT * – liquorvicar 2012-03-01 19:20:48

+0

如果我需要检索所有字段? @Matthew – 2012-03-01 19:28:09

0

使用别名

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

FROM ...

然后引用别名:

$name['TitleA'] 
0

停止使用SELECT *

显式列出您的列,然后根据需要允许您将它们别名。

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

而不是使用SELECT *,您将不得不按名称调用字段。当你这样做时,你可以为每个分配一个别名。

SELECT a.title AS aTitle, b.title AS bTitle, etc... 
0
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