如何在SQL中替换通配符URL?特定前缀URL替换方案求助
Hey there! Let's get this URL replacement sorted out for you. Based on your requirement—replacing any URL starting with https://oneweburl.com/cm entirely with https://anotherwebsite.com—here are the SQL statements you can use:
Step 1: Verify the records to update first (critical!)
Before running an UPDATE (which modifies data directly), always check which rows will be affected to avoid accidental changes:
SELECT url_column FROM your_table WHERE url_column LIKE 'https://oneweburl.com/cm%';
Replace your_table with your actual table name and url_column with the column storing the URLs.
Step 2: Run the update statement
Once you've confirmed the correct rows are targeted, use this UPDATE query to replace the URLs:
UPDATE your_table SET url_column = 'https://anotherwebsite.com' WHERE url_column LIKE 'https://oneweburl.com/cm%';
This query finds every record where the URL starts with https://oneweburl.com/cm (the % wildcard matches any characters after the prefix) and sets the URL to your desired target.
Alternative for precise prefix matching
If you prefer a more explicit way to check the prefix (avoiding any edge cases with wildcard matching), you can use the LEFT function (works in most SQL databases like MySQL, PostgreSQL, SQL Server):
UPDATE your_table SET url_column = 'https://anotherwebsite.com' WHERE LEFT(url_column, LENGTH('https://oneweburl.com/cm')) = 'https://oneweburl.com/cm';
This compares the first N characters of the URL (where N is the length of your target prefix) to ensure it's an exact match at the start.
Notes
- Always back up your data before running UPDATE statements, especially on production databases.
- If you're using a database that supports
STARTS WITH(like PostgreSQL), you can also useWHERE url_column STARTS WITH 'https://oneweburl.com/cm'as a more readable alternative to LIKE.
内容的提问来源于stack exchange,提问作者John




