good_evening
good_evening

Reputation: 21739

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? 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. Because now, if use just $name['title'] it returns tableA's title. And the above code unfortunately gives just an empty string.

Upvotes: 1

Views: 1237

Answers (5)

Aaron W.
Aaron W.

Reputation: 9299

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

Upvotes: 0

SuperRod
SuperRod

Reputation: 557

Instead of using SELECT *, you will have to call out the fields by name. When you do this, you can assign an alias to be used for each.

SELECT a.title AS aTitle, b.title AS bTitle, etc...

Upvotes: 0

Joe Stefanelli
Joe Stefanelli

Reputation: 135739

Stop using SELECT *!

Explicitly list your columns, which will then allow you to alias them as needed.

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

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101604

Use an alias

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

FROM ...

Then reference the alias:

$name['TitleA']

Upvotes: 0

Matthew
Matthew

Reputation: 25743

Instead of doing select *, you can put an alias on the columns as well.

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

Then your PHP would be something like:

$name['a_title']

Upvotes: 3

Related Questions