Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data from two tables with same column names

Tags:

sql

join

php

mysql

I have a table for users. But when a user makes any changes to their profile, I store them in a temp table until I approve them. The data then is copied over to the live table and deleted from the temp table.

What I want to achieve is that when viewing the data in the admin panel, or in the page where the user can double check before submitting, I want to write a single query that will allow me to fetch the data from both tables where the id in both equals $userid. Then I want to display them a table form, where old value appears in the left column and the new value appears in the right column.

I've found some sql solutions, but I'm not sure how to use them in php to echo the results as the columns in both have the same name.

like image 218
salmanhijazi Avatar asked Apr 16 '12 05:04

salmanhijazi


People also ask

Can 2 tables have same column name?

When two tables use the same column name(s), use table_name. column_name or table_alias. column_name format in SELECT clause to differentiate them in the result set. Use INNER JOIN whenever possible because OUTER JOIN uses a lot more system resources and is much more slower.

How can I get matching records from two tables?

(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.

How can I get common data from two tables in SQL?

The SQL intersect operator allows us to get common values between two tables or views. The following graphic shows what the intersect does. The set theory clearly explains what an intersect does. In mathematics, the intersection of A and B (A ∩ B) is the set that contains all elements of A that also belong to B.


1 Answers

Adding AS to a column name will allow you to alias it to a different name.

SELECT table1.name AS name1, table2.name AS name2, ...
  FROM table1
  INNER JOIN table2
    ON ...
like image 182
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 21:10

Ignacio Vazquez-Abrams