vendredi 9 janvier 2015

How to UPDATE a given mySQL table with random record from another table

I have a table tbl_random like this with about 3000 keywords and model_ids. Keyword are unique, model_ids are not:



+---------+------------+---------+---------+--------------+
| keyword | model_id | make | model | more_data |
+---------+------------+---------+---------+--------------+
| apple1 | 15 | | | |
| apple2 | 15 | | | |
| pear | 205 | | | |
| cherry | 307 | | | |
| melon | 5023 | | | |
+---------+------------+---------+---------+--------------+


and I have a second table tbl_products with about 500K records that contains the actual products and details about them:



+---------+--------+------------+
| make | model | more_data |
+---------+--------+------------+
| app1 | 15 | data1 |
| app1 | 15 | data2 |
| cher74 | 307 | data4 |
| melo2 | 5023 | data5 |
| pear53 | 205 | data3 |
+---------+--------+------------+


The common identifier between the two tables is model_id and model respectively.


What I need to do is to write an UPDATE MySQL query, which will update make model and more_data in tbl_random according to those criteria:


The query has to select one random row from tbl_products that matches every model_id from tbl_random for the unique keywords.


I was trying to do this in various ways using UPDATE, LEFT JOIN and SELECT STATEMENTS but cannot get it to work so far.


My latest statement, trying to update only make is this one, however it does not work - MySQL starts executing it and nothing happens except that I need to restart MySQL to get it available again:



UPDATE tbl_random
SET tbl_random.make =
(SELECT tbl_products.make FROM tbl_products
WHERE tbl_random.model_id = tbl_products.model
GROUP BY tbl_random.keyword
ORDER BY RAND())


The final desired output for tbl_random is this one:



+---------+------------+---------+---------+--------------+
| keyword | model_id | make | model | more_data |
+---------+------------+---------+---------+--------------+
| apple1 | 15 | app1 | 15 | data1 |
| apple2 | 15 | app1 | 15 | data2 |
| pear | 205 | pear53 | 205 | data3 |
| cherry | 307 | cher74 | 307 | data4 |
| melon | 5023 | melo2 | 5023 | data5 |
+---------+------------+---------+---------+--------------+


Any help or suggestions will be appreciated!





Aucun commentaire:

Enregistrer un commentaire