Jason
Jason

Reputation: 556

MySQL append unrelated table

I need to append Table1 to Table2 in such a way that no information is duplicated.

Example:

Table1

Name   | Age
-------|-----
Jason  | 30
John   | 40
Joseph | 50
Bob    | 60

Table2

Type
--------
Dog
Cat
Fish

I need a join to produce

Name  | Age | Type
------|-----|-------
Jason | 30  | Dog
John  | 40  | Cat
Joseph| 50  | Fish
Bob   | 60  | NULL

So it only returns four rows and not 12 or more. There is no ID or other information that can relate the two tables.

Upvotes: 1

Views: 205

Answers (2)

Nathan
Nathan

Reputation: 2775

Try this:

SELECT  A.rank, A.NAME, A.AGE, B.TYPE FROM
(select @rownum:=@rownum+1 ‘rank’, T1.NAME, T1.AGE from 
TABLE1 T1, (SELECT @rownum:=0) r) A
LEFT JOIN
(select @rownum:=@rownum+1 ‘rank’, T2.TYPE from 
TABLE2 T2, (SELECT @rownum:=0) r) B
ON A.rank = B.rank

And check these:

ROW_NUMBER() in MySQL

http://craftycodeblog.com/2010/09/13/rownum-simulation-with-mysql/

http://jimlife.wordpress.com/2008/09/09/displaying-row-number-rownum-in-mysql/

Upvotes: 2

Vikram
Vikram

Reputation: 4190

If possible try altering both tables to add index column and then join on index column this way

ALTER table1 add id INT NOT NULL;

ALTER table2 add id INT NOT NULL;

select table1.Name, table1.Age, table2.Type from table1 inner join table2 on table1.id= table2.id

Upvotes: 0

Related Questions