Creating a complicated MySQL Update Query - mysql

I am trying to create an UPDATE query that will replace the NameID field on a table called TimeStamps with the user's id field value from another table called Names. Here is some sample data.
Names Table
id:1
name:John
password:1234
TimeStamps Table
id:1
name:**John**
timestamp:01/01/2000 12:00:00
I want to replace the Name field in the TimeStamps table with the corresponding id value from the Names table. I'm not entirely sure on how to write the query but I know it starts with something like this.
UPDATE TimeStamps
SET NameID=(NamesTableReference)
WHERE NameID=(TimeStampsTableReference);
This way I can start to run queries against the user's id and not the user's Name. We have more than one user with the same name and it doesn't pull the right data because it is pulling multiple users. I can update the data manually but there are several hundred thousand rows in the table and that would take entirely too much time. Can anyone shed some light on what I need to add/change in the query below? Thanks!

I think you just want a join:
update timestamps t join
names n
on t.id = n.id
set t.name = n.name;
However, the update shouldn't be necessary. You have an id connecting the two tables. Just use it when you are using timestamps. That is, use a join to look up the name rather than storing it in both places -- and running the risk that the names associated with an id somehow end up different in the two tables.

It looks like this query did the trick.
UPDATE TimeStamps t, Names n
SET t.NameID = n.id
WHERE t.NameID = n.Name
Thanks everyone for your input and your help! Hope this can help someone else in the future!

Related

Get column content from one table and use it to get id from other table

Sorry for the bad description, not sure what to call this.
I'm trying to migrate a bad database structure to a better one.
The old storage, lets say customer name in say invoice table.
The new I going to need a ref to customer-table so that more information about the customer can be queried if needed.
So, to not completely break all the old entries, I would like a query that take col2,col3,col4 from tbl1 and and queries tbl2,tbl3 and tbl4 to get and ID of
each of the content of the columns.
Then I would want to update the row in tbl1 with these ID's in their respectable column.
The thing is, I have no idea about how to do this.
I don't even know what to search for to learn about it.
Better example:
Imagen you have pet-owner table. The old table had:
Owner: John
pet: Dog
But now I have a table for owners and a table for pets, so I want to update the columns in pet-owner table so for each row it will (in this case) search ower-table for 'John' and pet-table for 'dog' and return their ID and update the pet-owner table with that.
You'll have a much easier time if you add new columns to hold the ids, populate them, and then drop the old columns later.
If you do that, your update would be like:
update pet_owner
inner join pet on pet_owner.pet_name = pet.name
inner join owner on pet_owner.owner_name = owner.name
set pet_owner.pet_id = pet.id
pet_owner.owner_id = owner.id
;

Getting rows in Microsoft Access to refer to other rows

I have a Microsoft Access table of data with 3 fields: "part_number", "date_of_price_change" and "new_price", but I need to convert the "new_price" field to show the "price_change", rather than the full "new_price" of each part on each date.
This will obviously involve some process that looks at each unique part number on each date and looks up the price of the record with the same part number with the next earliest date and deduct the prices to get the price change.
Problem is, I have no idea how to do this in Access and there are too many records for Excel. Can anyone assist with how to do this in Access? (Note that date changes can happen any time and are not periodic).
Many thanks in advance.
Ana
Add the new column price_change as a Money data type, then run a query something like below. Make sure you backup the table first with an APPEND table to a new table, just in case. Since it is a new column i may not matter.
UPDATE
T1
SET
T1.price_change = T1.new_price - Nz((SELECT top 1 T2.new_price from MyTable T2 WHERE T2.part_number = T1.Part_Number ORDER BY date_of_price_change DESC),0)
FROM
MyTable T1

mysql query using column values as parameter in query phpMyAdmin

I have a query i have been working on trying to get a specific set of data, join the comments in duplicate phone numbers of said data, then join separate tables based on a common field "entry_id" which also happens to be the number on the end of the word custom_ to pull up that table.
table named list and tables containing the values i want to join is custom_entry_id (with entry_id being a field in list in which i need the values of each record to replace the words in order to pull up that specific table) i need entry_id from the beginning part of my query to stick onto the end of the word custom for every value my search returns to get the fields from that custom table designated for that record. so it will have to do some sort of loop i guess? sorry like i said I am at a loss at this point
this is where i am so far:
SELECT * ,
group_concat(comments SEPARATOR '\r\n\r\n') AS comments_combined
FROM list WHERE `status` IN ("SALEA","SALE")
GROUP BY phone_number
//entry_id is included in the * as well as status
// group concat combines the comments if numbers are same
i have also experimented on test data with doing a full outer join which doesnt really exist. i feel if you can solve the other part for me i can do the joining of the data with a query similar to this.
SELECT * FROM test
LEFT JOIN custom_sally ON test.num = custom_sally.num
UNION
SELECT * FROM test
RIGHT JOIN custom_sally ON test.num = custom_sally.num
i would like all of this to appear with every field from my list table in addition to all the fields in the custom_'entry_id' tables for each specific record. I am ok with values being null for records that have different custom fields. so if record 1 has custom fields after the join of hats and trousers and record 2 has socks and shoes i realize that socks and shoes for record 1 will be null and hats and trousers for record 2 will be null.
i am doing all this in phpmyadmin under the SQL tab.
if that is a mistake please advise as well. i am using it because ive only been working with SQl for a few months. from what i read its the rookie tool.
i might be going about this all wrong if so please advise
an example
i query list with my query i get 20,000 rows with columns like status, phone_number, comments, entry_id, name, address, so on.
now i want to join this query with custom fields in another table.
the problem is the custom tables' names are all linked to the entry_id.
so if entry_id is 777 then the custom table fields are custom_777
my database has over 100 custom tables with specials fields for each record depending on its entry_id.
when i query the records I don't know how to join the custom fields that are entry_id specific to the rest of my data.i will pull up some tables and data for a better example
this is the list table:
this is the custom_"entry_id"
Full Outer Join in MySQL
for info on full outer joins.

Updating several table columns based off a Select Query

So this is my Select Query called qryHoursSUM.
SELECT DAL.Project
, DAL.Unit
, DAL.Activity
, Sum(([EndTime]-[StartTime])*24) AS Hours
FROM DAL INNER JOIN UnitTbl
ON (DAL.Project=UnitTbl.Project) AND (UnitTbl.Unit=DAL.Unit)
GROUP BY DAL.Project, DAL.Unit, DAL.Activity;
I'm trying to get it to update to the corresponding *** Actual field and matching row in my Table called UnitTbl, which has the Project and Unit fields as a composite primary key. I cant seem to get it to work. I've first tried running a update query based on the select query but received an "Operation must use an updateable query", and found out that its not possible. I've made a make table query call qrySumHoursTbl to turn the qryHoursSUM into a table
SELECT qryHoursSUM.* INTO SumHoursTbl
FROM qryHoursSUM;
Then created an update query called qryUpdateUnitTbl to just update the 002 Actual field
UPDATE SumHoursTbl INNER JOIN UnitTbl
ON (SumHoursTbl.Unit = UnitTbl.Unit)
AND (SumHoursTbl.Project = UnitTbl.Project)
SET UnitTbl.[002 Actual] = [Hours]
WHERE (([Activity]="002 Drafting Submittals"));
Is it possible to have an update query to update multiple fields at once or would I have to make a update for each field i want to update?
Also, for some reason it only update the UnitTbl with whole numbers only, I need to have it show up to 2 decimal places. After working with so many copies, I completely forgot to change the field size to double. After changing that, its showing up to 2 decimal places
My end goal is to be able to let a user click on a button that shows a variance report of hours for each units Budgeted hours and Actual hours (which would be [*** Budget] - [*** Actual]) Any tips for things to consider along the way to get there is appreciated, I've trying to figure this out for a week now.

How do I make the rows of a lookup table into the columns of a query?

I have three tables: students, interests, and interest_lookup.
Students has the cols student_id and name.
Interests has the cols interest_id and interest_name.
Interest_lookup has the cols student_id and interest_id.
To find out what interests a student has I do
select interests.interest_name from `students`
inner join `interest_lookup`
on interest_lookup.student_id = students.student_id
inner join `interests`
on interests.interest_id = interest_lookup.interest_id
What I want to do is get a result set like
student_id | students.name | interest_a | interest_b | ...
where the column name 'interest_a' is a value in interests.name and
the interest_ columns are 0 or 1 such that the value is 1 when
there is a record in interest_lookup for the given
student_id and interest_id and 0 when there is not.
Each entry in the interests table must appear as a column name.
I can do this with subselects (which is super slow) or by making a bunch of joins, but both of these really require that I first select all the records from interests and write out a dynamic query.
You're doing an operation called a pivot. #Slider345 linked to (prior to editing his answer) another SO post about doing it in Microsoft SQL Server. Microsoft has its own special syntax to do this, but MySQL does not.
You can do something like this:
SELECT s.student_id, s.name,
SUM(i.name = 'a') AS interest_a,
SUM(i.name = 'b') AS interest_b,
SUM(i.name = 'c') AS interest_c
FROM students s
INNER JOIN interest_lookup l USING (student_id)
INNER JOIN interests i USING (interest_id)
GROUP BY s.student_id;
What you cannot do, in MySQL or Microsoft or anything else, is automatically populate columns so that the presence of data expands the number of columns.
Columns of an SQL query must be fixed and hard-coded at the time you prepare the query.
If you don't know the list of interests at the time you code the query, or you need it to adapt to changing lists of interest, you'll have to fetch the interests as rows and post-process these rows in your application.
What your trying to do sounds like a pivot.
Most solutions seem to revolve around one of the following approaches:
Creating a dynamic query, as in Is there a way to pivot rows to columns in MySQL without using CASE?
Selecting all the attribute columns, as in How to pivot a MySQL entity-attribute-value schema
Or, identifying the columns and using either a CASE statement or a user defined function as in pivot in mysql queries
I don't think this is possible. Actually I think this is just a matter of data representatioin. I would try to use a component to display the data that would allow me to pivot the data (for instance, the same way you do on excel, open office's calc, etc).
To take it one step further, you should think again why you need this and probably try to solve it in the application not in the database.
I know this doesn't help much but it's the best I can think of :(