简体   繁体   中英

Alter MySQL table column to match id's from another table

Consider the following two MySQL tables:

companies
-----------------------
id ticker
1  AA
2  AAPL
3  ABT
4  AEP

tweets
-----------------------
tweet_id query (etc...)
1        $AA
2        $AA
3        $AAPL
4        $ABT
5        $AA
6        $AEP
7        $AEP

The table "companies" contains over 700 ticker symbols for various stocks. The table "tweets" contains millions of tweets. These tweets were gathered by querying Twitter.com for each ticker, prepended by "$", as this is the convention on Twitter when talking about a certain stock. I now would like to normalize the tweets table, as follows:

tweets
-----------------------
tweet_id query (etc...)
1        1
2        1
3        2
4        3
5        1
6        4
7        4

So now, the tweet with tweet_id one was obtained by querying for ticker with id 1, being AA (the "$" is not necessary to store in the database anymore). Now my question would be: is there a way to update the query-column in the tweets-table with one sql-query? Your help would be greatly appreciated, since I see a lot of work ahead (by using PHP, perhaps) if this is not possible :)

You can use an update join. Something like this:

UPDATE tweets t
    JOIN companies c ON t.query = CONCAT('$', c.ticker)
SET t.query = c.id;

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