简体   繁体   中英

MySQL Join tables without having common column at all, just by order

I have the same problem described in this other question:

MySQL / PHP Joining tables without always having common column

But my tables don't have ane field in common, and i only want to join them "the first one with the firs one", "the second one with the second one" and so on.

Example:

Table_1

  • john
  • mary
  • charles

Table_2

  • smith
  • goodman
  • bush

TableResult

  • john | smith
  • mary | goodman
  • charles | bush

Tables should allways have the same ammount of items, but if not, the unexisting items could be filled with null, as "henrry | null".

Perhaps it could be done adding first a field to number each row, or something so, but performance is critical here.

This really isn't a good idea, and can never be guaranteed consistent results, but you can get the row number of each table and use that as your joining field.

Try somemthing like this:

SELECT Field1, Field2
FROM (SELECT Field1, @curRow := @curRow + 1 AS row_number
      FROM Table1
         JOIN    (SELECT @curRow := 0) r) t1
 JOIN (SELECT Field2, @curRow2 := @curRow2 + 1 AS row_number
      FROM Table2
         JOIN    (SELECT @curRow2 := 0) r) t2 on t1.row_number = t2.row_number

And here is the SQL Fiddle .

This will only work if both tables have the same number of rows. If not, you'll be missing data...

Good luck.

If you want performance just use integer primary keys but you do need keys. You CAN NOT AND SHOULD NOT do it the way you described. :)

Edit:

Given that your requirements are specifically to achieve random results, I think you can make use of a cross join .

The following fiddle captures my effort to demonstrate this.

--

Otherwise, if your data is truly constant (in which case, why are you using a database?) then it could produce consistent results - but you could just as easily define keys and be done with it. If not, consider what happens with your expectation that "the unexisting [sic] items could be filled with null" when you grow the database:

Before

Table 1

foo
bar

Table 2

qux

Result

foo qux
bar null

After

Table 1

foo
bar
baz

Table 2

qux
quxx

Result

foo qux
bar quxx
baz null

You can't add baz quxx to the database.

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