Update values of one column with multiple values - mysql

There is a table and that table has a column with a name country and I need to change values at that column in one query instead of multiple queries.
In this query, I change any value with Egypt to be 1
UPDATE subscribers
SET country = 1 WHERE country = 'Egypt';
in this query, I change any value with Qatar to be 2
UPDATE subscribers
SET country = 2 WHERE country = 'Qatar';
Any help to make these two queries in one?

Consider:
UPDATE subscribers SET country =
CASE
WHEN country = "Egypt" THEN 1
WHEN country = "Qatar" THEN 2
ELSE country
END
;
Now imagine doing that expression for many more countries. Instead join to a table that 'maps' data association (a master table of country names). Join on CountryName fields and update destination table CountryName field with ID from 'mapping' table. Convert to number type field. Or play it safe and update to another field and when all looks good, delete the original field.

You can use a case expression in MySQL:
UPDATE subscribers
SET country = (CASE WHEN country = 'Egypt' THEN 1 ELSE 2 END)
WHERE country IN ('Egypt', 'Qatar');
However, I would recommend using a derived table:
UPDATE subscribers s JOIN
(SELECT 'Egypt' as country, '1' as new_country UNION ALL
SELECT 'Qatar' as country, '2' as new_country
) x
USING (country)
SET s.country = x.new_country;

Related

INNER JOIN Statement returns multiple rows instead of one

There are two tables, namely sku and country without any matching columns. I need to retrieve a unique field printable_name from country table based on the value of c_code in sku table. c_code column has multiple same country codes(Example: 124) while numcode column in the country table contains the same country code but only once because it is a unique field. The row that has the unique numcode has the country name which I am finally trying to retrieve. The result from my SQL query below gives multiple rows instead of just one from the country table. I just want one record only from country table, which is printable_name
I am trying to combine the following SQLs into one with the JOIN statement.
$vendor_sku = $my_line_item['sku'];
// Build SQL to retrieve country name.
$sql = "SELECT c_code FROM sku WHERE item_sku = '" . $vendor_sku . "'";
$sql = "SELECT printable_name FROM country WHERE numcode = '" . $c_code . "'";
SELECT country.printable_name
FROM country INNER JOIN sku ON country.numcode = sku.c_code
WHERE country.numcode = "124"
Part of my country table is :
part of sku table is:
Country table has only one entry for numcode 124 as seen below.
Try:
SELECT a.printable_name
FROM country a
WHERE
1=1
and a.numcode = '124'
and exists (select 1 from sku s where a.numcode = s.c_code)
I just want the record only from country table
Then why are you using the sku table?
SELECT c.printable_name
FROM country c
WHERE c.numcode = 124;
Note: I assume that 124 is a number, so I removed the quotes. If it is a string, then use a string with single quotes, '124'.

MySQL select and match two tables and update column based on matched data

It seems difficult for me to thats why I need your help. So basically, I got two tables named xp_pn_resale and xp_guru_properties. What I need to do is update or set the column postal_code from table xp_pn_resale based from the data from another table. So here are my tables
My xp_pn_resale table, I wrote query like this in order to show you
SELECT postal_code,
block,
concat(block,' ', street_name) as address
FROM xp_pn_resale
where street_name like '%ANG MO KIO%';
And I get the result like this
As you can see, there are null values there and there are some postal_code that has values because I manually update them based on what I searched. I just want to automatically fill the postal_code from the query I got from other table.
Here is my xp_guru_properties table and I wrote query like this in order to show you
SELECT property_name as GURU_PROEPRTY_NAME,
property_type as GURU_PROPERTY_TYPE ,
JSON_UNQUOTE(JSON_EXTRACT(xp_guru_properties.json, '$.postcode') )as GURU_POSTCODE
FROM xp_guru_properties
where property_type like '%HDB%' AND property_name like '%ang mo kio%';
And the result is like this
xp_guru_properties got a column property_type which is a bit similar in the concatinated columns of block and street_name from other table I named it as GURU_PROPERTY_NAME.
As you can see, there is the virtual column named GURU_POSCODE. The values of that column is what I want to fill in the postal_code column from xp_pn_resale table. I was doing it manually to update the postal_code by doing
UPDATE xp_pn_resale
SET postal_code = 560110
WHERE street_name LIKE '%ANG MO KIO%'
AND block = 110
which is very tedious to me. Does anyone know how could I automatically update it based on the queries I showed ? Help will be appriciated.
EDIT: I wrote a JOIN query like this but this is for the record Lingkong Tiga which i manually filled all the postal_code
select distinct
JSON_UNQUOTE(json_extract(g.json, '$.postcode')) postcode,
JSON_UNQUOTE(json_extract(g.json, '$.name')) name,
JSON_UNQUOTE(json_extract(g.json, '$.streetnumber') )streetnumber,
p.block, p.street_name, p.postal_code
from xp_pn_resale p
inner join xp_guru_properties g
on g.property_name = concat(p.block, ' ', p.street_name)
where g.property_type like '%HDB%' AND g.property_name like '%Lengkong Tiga%'
I got result like this
Join the two tables and update.
UPDATE xp_pn_resale AS r
JOIN xp_guru_properties AS p ON concat(r.block,' ', r.street_name) = p.property_name
SET r.postal_code = JSON_UNQUOTE(JSON_EXTRACT(xp_guru_properties.json, '$.postcode') )
WHERE r.street_name like '%ANG MO KIO%'
AND p.property_type like '%HDB%' AND p.property_name like '%ang mo kio%'
AND r.postal_code IS NULL

Change Foreign Key Value in Access Query

Here is a small example of what I would like to accomplish.
Table 1: Person
ID
FirstName
HairColor_ID
Table 2: HairColor
ID
Color
I have Query 1 where I give it a color parameter(c) and it returns the ID of that Hair Color
SELECT HairColor.ID
FROM HairColor
WHERE (([HairColor].[Color]=[c]));
Now in Query 2, I have the Person table and the Query 1. In the field, I want to choose ID 2 of person and change its HairColor_ID according to the Query 1 result(which should return an ID), Query 2 is below:
UPDATE Person INNER JOIN Query1 ON Person.ID = Query1.ID SET
Person.HairColor_ID = [Query1]![ID]
WHERE (((Person.ID)=2));
I would assume [Query1]![ID] returns the ID.
Basically all I want to do is update the HairColor_ID by giving the Color Value as a parameter. How would I do this?
Essentially what you want is to update a CROSS JOIN between Person and HairColor. You don't need Query1, and to me at least the mechanism is clearer without it.
PARAMETERS c Text ( 255 );
UPDATE Person, HairColor
SET Person.HairColor_ID = [HairColor].[ID]
WHERE Person.id=2 AND HairColor.Color=[c];
You are trying to join the Person table with Query1 via Person.ID = Query1.ID but Query1.ID isn't the ID of a person but of a haircolor...
This query should change the HairColor of person 2 to the color you enter as the parameter c:
UPDATE Person, Query1 SET Person.HairColor_ID = [Query1].[ID]
WHERE (((Person.ID)=2));

How to update values for several columns in a Table with a single query?

I have a table something like below,
ID Name EMail Gender
and there are values already in this table.
Now, I used below query to add age.
alter table tblPerson add Age int
Now, my row structure looks like
ID Name EMail gender Age
Now, I have list of ages. Any query to add these ages into newly created column?
All the ages are sorted according to ID. So no IF logic required. I just need to add column data.
Thanks.
Store the values in a temporary table with the id. Then use a join:
update t join
idages ia
on t.id = io.id
set t.age = ia.age;
You can also do this with a giant case expression, but that is prone to error:
update t
set t.age = (case when id = id1 then age1
when id = id2 then age2
when id = id3 then age3
. . .
end)
where t.age in (id1, id2, id3, . . .);

Complicated MySql Update Join Query

Have is an example of the problem I'm facing. The database tables are a little different than usual, but needed to be setup this way.
Items: id, order_id, other fields
Items_Drinks: id, drinks, other fields
Orders: id, other fields
Orders_Drinks: id, drinks, other fields
I need to have an update query that will update the Orders_Drinks table with the sum of the Items_Drinks drinks field that have the same order_id as Orders_Drinks id field.
Items: 1 1 ...
Items: 2 1 ...
Items_Drinks: 1 4 ...
Items_Drinks: 2 5 ...
Orders: 1 ...
Orders_Drinks: 1 9 ...
The Orders_Drinks is currently correct, but if I were to update Items_Drinks with id of 1 to 5, I would need an update command to get Orders_Drinks with id 1 to equal 10.
It would be best if the command would update every record of the Orders_Drinks.
I know my database is not typical, but it is needed for my application. This is because the Drinks table is not needed for all entries. The Drinks table has over 5000 fields in it, so if every record had these details the database would grow and slow for no real reason. Please do not tell me to restructure the database, this is needed.
I am currently using for loops in my C# program to do what I need, but having 1 command would save a ton of time!
Here is my best attempt, but it gives an error of "invalid group function".
update Orders_Drinks join Items on Items.order_id=Orders_Drinks.id join Items_Drinks on Items_Drinks.id=Items.id set Orders_Drinks.drinks=sum(Item_Drinks.drinks);
I think this is what you're wanting.
Edited:
UPDATE `Order_Drinks` a
SET a.`drinks` = (SELECT SUM(b.`drinks`) FROM `Items_Drinks` b INNER JOIN `Items` c ON (b.`id` = c.`id`) WHERE a.`id` = c.`order_id`)
That should give you a total of 9 for the Order_Drinks table for the row id of 1.
This is assuming that Orders.id == Orders_Drinks.id and that Items.id == Items_Drinks.id.
You need to do an aggregation. You can do this in the join part of the update statement:
update Orders_Drinks od join
(select i.order_id, sum(id.drinks) as sumdrinks
from Items i join
Items_Drinks id
on id.id = i.id
) iid
on iid.order_id = od.id
set od.drinks = iid.sumdrinks;
Something like this will return the id from the orders_drinks table, along with the current value of the drinks summary field, and a new summary value derived from the related items_drinks tables.
(Absent the name of the foreign key column, I've assumed the foreign key column names are of the pattern: "referenced_table_id" )
SELECT od.id
, od.drinks AS old_drinks
, IFNULL(td.tot_drinks,0) AS new_drinks
FROM orders_drinks od
LEFT
JOIN ( SELECT di.orders_drinks_id
, SUM(di.drinks) AS tot_drinks
FROM items_drinks di
GROUP BY di.orders_drinks_id
) td
ON td.orders_drinks_id = od.id
Once we have SELECT query written that gets the result we want, we can change it into an UPDATE statement. Just replace SELECT ... FROM with the UPDATE keyword, and add a SET clause, to assign/replace the value to the drinks column.
e.g.
UPDATE orders_drinks od
LEFT
JOIN ( SELECT di.orders_drinks_id
, SUM(di.drinks) AS tot_drinks
FROM items_drinks di
GROUP BY di.orders_drinks_id
) td
ON td.orders_drinks_id = od.id
SET od.drinks = IFNULL(td.tot_drinks,0)
(NOTE: the IFNULL function is optional. I just used it to substitute a value of zero whenever there are no matching rows in items_drinks found, or whenever the total is NULL.)
This will update all rows (that need to be updated) in the orders_drinks table. A WHERE clause could be added (after the SET clause), if you only wanted to update particular rows in orders_drinks, rather than all rows:
WHERE od.id = 1
Again, to get to this, first get a SELECT statement working to return the new value to be assigned to the column, along with the key of the table to be updated. Once that is working, convert it into an UPDATE statement, moving the expression that returns the new value down to a SET clause.