简体   繁体   中英

How to get value from one table column when two columns of the same name exist in an sql join

I am currently faced with the problem of trying to get a value when I have joined two tables with columns of the same name eg: table1.date and table2.date (date is different in each table) how would I get the "date" of table 1 in this instance. I am currently running

while($row = $mysqliquery->fetch_object()) {

is there any way that I could use some form of syntax to retrieve the date from table 1 within the following code

$row->date eg $row->table1.date or something

If not how else would I be able to accomplish this? Thanks.

You should differentiate between 2 columns with the same name by using an alias for one or both of the 2 columns in the query like this

SELECT a.`date`, b.`date` as b_date
FROM table1 a
    JOIN table2 b ON a.id = b.a_id
WHERE some specific criteria

Now when your retrieve the ROW each date has its own unique name ie

$row->date;
$row->b_date;

I was thinking more along the lines of this ( ficticious ) pseudo sql

select a.`account_id`, a.`date` as 'account_date', u.`date` as 'signup_date'
from `accounts` a
left outer join `users` u on u.`uid`=a.`uid`

Each table has a column called date but in the sql they are each referenced with a unique alias. You cannot have two columns in the same query with the same name or you'll get errors, so you give them an alias. The tables are also aliased in this code - it really helps simplify things in my opinion... Anyway, just a quick example to illustrate how you might approach this - others may have a different approach from which I might learn new tricks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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