简体   繁体   中英

Adding two tables with no column in common in MySQL

I have two tables my database. I just want to append these two tables. I am not able to find the solution for it

Table 1 -

 names
    First_name    Last_name
      Navjot        Singh
      Ram            Gopal
      Naveen         Kumar

Table 2 -

address
            address    Pin
             Delhi    90007
             Lucknow  90003
             Mumbai   60008

How to get the data from these two tables in the following format:

First_name      Last_name      address        Pin

  Navjot        Singh            Delhi       90007
  Ram           Gopal           Lucknow     90003
  Naveen        Kumar            Mumbai     60008

These are just sample tables. I want to do this thing on 50,000 rows. Number of rows are same in my both the tables. I have tried cross join. I have tried following sql as well:

Select * from names,address;

It increases the total number of rows. I even tried union, but it did not work.

It is something like cbind.data.frame in R. How to do it in mysql? any help would be appreciated.

The problem is that you have no column for the join. Assuming that you have some column to specify the ordering, you can do:

select t1.*, t2.*
from (select t.*, (@rn := @rn + 1) as seqnum
      from table1 t cross join (select @rn := 0) params
      order by t.id
     ) t1 join
     (select t.*, (@rn2 := @rn2 + 1) as seqnum
      from table2 t cross join (select @rn2 := 0) params
      order by t2.id
     ) t2
     on t1.seqnum = t2.seqnum;

This generates a sequential key for each row in each of the tables. This key is then used for the joins.

There may be an easier way but off the top of my head

Select I.*, j.* from
   (Select *, @row:@row+1 as rowid from names) I
Left join
   (Select *, @adid:@adid+1 as rowid from address) j
Using(rowid);

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