Way to update entire column using row index and hardcoded value in Mysql
P粉362071992
2023-08-26 15:24:30
<p>I want to update the entire <strong>email</strong> column with the row index email@gmail.com. </p>
<p>This is the data in my table</p>
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>abc@gmail.com</td>
</tr>
<tr>
<td>23</td>
<td>pqr@gmail.com</td>
</tr>
</tbody>
</table>
<p>This is the output I want</p>
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>1email@gmail.com</td>
</tr>
<tr>
<td>23</td>
<td>2email@gmail.com</td>
</tr>
</tbody>
</table>
<p>I tried the query below but didn't get the output I expected. </p>
<pre class="brush:php;toolbar:false;">;with C as
(
select email,row_number() over(order by id asc) as rowid
from cus
)
update C
set email = rowid 'email@gmail.com'</pre>
<p>That's not just 3 rows, I have over 500 rows in my <code>cus</code> table. It would be better if someone could give me a solution that doesn't require looping. Please help me create a SQL query. Thanks. </p>
This seems to work, but I believe there is a more elegant solution that doesn't require using join...
Full Test
Maybe this is what you want to do:
Connect the table you want to update (
cus
) with thecte
ofC
, and then update accordingly.Here is a demo
@QisM raised concerns about the syntax when
email
is not unique, and since the OP didn't mention it, I agree that ifemail
is indeed not unique, this is not a solution. So I modified the syntax slightly:Now
cte
withid
, and in theJOIN C ON ..
condition, I added a check that matchesid
. After testing, this will fix the issue if the email is not unique.