1

I have two tables like indicated below: Table1:

name    surname    age
----    -------    ---
 a         b       null
 c         d       null

Table 2:

age
---
 1 
 4

I want to combine them into first table (Table1) like

name    surname    age
----    -------    ---
 a         b        1
 c         d        4

(they have the same number of rows) How can I combine them?

6
  • 4
    uhmm what is their relationship? Commented Dec 29, 2012 at 8:09
  • How are you connecting the users in Table 1 with the age in Table 2? Or are you trying to do by row number? Commented Dec 29, 2012 at 8:11
  • The relation is their row numbers. Commented Dec 29, 2012 at 8:15
  • @JoshuaJeanThree bad design, you should recreate it by giving primary keys. Commented Dec 29, 2012 at 8:17
  • I know it is bad. But it was given to me in a dataset. Commented Dec 29, 2012 at 8:22

1 Answer 1

7

maybe you want this,

SELECT a.Name, a.SurName, b.Age
FROM
  (
    SELECT @row := @row + 1 RankNo,
           Name, Surname
    FROM   Table1, (SELECT @row := 0) r
  ) a
  INNER JOIN
  (
    SELECT @row1 := @row1 + 1 RankNo,
           Age
    FROM   Table2, (SELECT @row1 := 0) r
  ) b ON a.RankNo = b.RankNo
Sign up to request clarification or add additional context in comments.

4 Comments

how can we be sure that rows will always be returned in the same order? theoretically mysql could return rows with any order, unless you specify an order by
@fthiella mysql could return rows with any order. nope. it depends on which field you have set an index first.
without knowing if there's an index or not, rows order can't be determined. But I am also not sure that an index would solve this problem, of course MySql would use an index to return rows and to sort rows, but I am not sure if that's guaranteed or documented somewhere.
pls see here: dev.mysql.com/doc/refman/5.5/en/innodb-index-types.html it looks like that, when no explicit index is given, default fifo order is always guaranteed for InnoDB tables. So your answer should be correct!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.