سؤال

been troubling around for hours on this seeing I'm no expert.

I've two tables t1 and t2 and need to update each row in t1 that has a match in t2. t1 contains a serialkey field in the format xxx-xxx-xxx-xxx-xxx t2 contains a serialkey field in the format xxxxxxxxxxxxxxx

I thought I could use an UNION ALL but I'm not achieving what I'm trying to do. Since the one table contains the serial with dashes I thought to remove them like this.

SELECT serialkey FROM
(SELECT replace(serialkey,'-','') as serialkey FROM t1 
UNION ALL
SELECT serialkey FROM t2 ) tbl
GROUP BY serialkey

I also experimented with an HAVING count, though in the first and second versions I can't seem to either get a count, nor to group them, as to find all the rows in t1 that has a match in t2 with the intent to then update a column in t2 to say match found (so that I only have to run this once).

SELECT serialkey
FROM (
SELECT replace(serialkey,'-','') serialkey FROM t1
UNION ALL
SELECT serialkey FROM t2
) tbl
GROUP BY serialkey
HAVING count(*)= 2 <<--- 2 shows none and 1 shows all rows combined
ORDER BY serialkey;

Finally note that t1 will contain some 150,000 rows and t2 around 300,000; There would likely by about 110,000 matches between t1 and t2 that I want to edit as mentioned (PHP). I tried some left join as well, ended up not being able to access phpmyadmin for 15 minutes, likely my own bad though I guess this query is rather big as to needing the best code.

Both results above simply lists all my records from both tables!

Any help appreciated, thank you.

Chris

هل كانت مفيدة؟

المحلول

Having the serialkey value formatted in one table and unformatted in another pretty much kills any chance of optimizing the query, but with 300K rows it shouldn't take that long - probably many seconds rather than many minutes.

Basically what you need is an INNER JOIN. This will give you a list of all serial keys which are in t1 and t2:

SELECT t1.SerialKey
FROM t1
JOIN t2 ON REPLACE(t1.SerialKey, '-', '') = t2.SerialKey

You can use the same join logic in an update:

UPDATE t1
JOIN t2 ON REPLACE(t1.SerialKey, '-', '') = t2.SerialKey
SET t1.whatever = 'whatever'

نصائح أخرى

UPDATE t1,t2 
SET t1.serialkey = t2.serialkey
WHERE t2.serialkey = REPLACE( t1.serialkey,  '-',  '')

I assumed you want to copy the serial number from t2 and insert it without the dashes in t1 if there is a match. plz do don't use this query in a real db without a back up :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top