Delete row from one table based off another table - mysql

I have been trying to 3 days but can’t figure it out
I have two tables
One table called se with 12 columns and 1 unique ID. One column is npcid and it is not unique in this table.
There’s another table called npcs where there is a unique id. The unique id from this table can appear multiple times in the se table.
I need to delete every entry from the se table based off of the id in the npc table. I want delete every row in se where the npcid is not listed on the npc table. I have been researching for days and can’t seem to figure it out. I’ve been trying the join command
I am using sql 7.4.3 10.3.37-MariaDB-0ubuntu0.20.04.1 and I did download the npc table and just copied the ids and was able to use
DELETE FROM se WHERE npcid NOT IN (100,
200,
300);
But I noticed it was missing items probably due the fact it is over 1,000,000 entries and over 50,000 exclusions.
Any help would be great as I am really struggling with this join command, I can’t even get someone to give me a simple example. I feel like it shouldn’t be that hard to delete data based on data in another table but I’m just learning and I’m sure it is simmering I’m obviously doing wrong
I have tried over 300 commands, I have been reading and researching for about 3 days I’ve tried manually coping the ids and using a different command but it is missing data
I was pointed to an answer which has the opposite effect, I do not want to delete the ids based on the ids in the other table but rather those are the ids I want to keep

I did eventually figure it out, I’m not sure why I was having so many issues but what I did was
DELETE
FROM table
WHERE column2 NOT IN
(SELECT column2 FROM npc);

Related

Multiple table update design in Access

I have learned more, and was compelled to find the solutions, mind changed.
PS dear experts, your help is appreciated in the time-saving nature of having forums and discussion in the first place, and also is mined for usefulness, not street cred. get helping or get off. The time I wasted reading posts where the answer was "I don't understand what you are trying to do..." and then questioning the OP with animus or incredulity, or suggesting some unrelated answer further confusing issues, is seemingly the problem with the world these days, if you want to help, help
Original Post:
Ok so as per the comments, thanks to ANYONE who volunteers any help with this problem.
I have a table and relationship design problem.
I have a table with a pk auto and I want to have a related table with a related column incrementally numbered that updates every time new data is entered in the form that is bound to it. It needs to update the related rows in the autonumbered table's key.
---the answer was to join the table on the autonumbered field.
The autonumber of the first table (main recordsource) is just an ID. I think I need two Primary Keys as I need to update the related record with that number in the entry form and move to NextRec but update the pk in the main table and move to NewRec , how do I join (see jpg image)?
I want enter results and update that existing record but update the adjoining pk so that a new record is created in the main table.
Tourney
more in depth:
From yours
My desired form
note that the calculation table feeds the upcoming games table, where a query shows the players recent results. I would like to split the upcoming results to show the players' recent game history, the second tab I would like to enter either one result or many results at a time. I hope I am clearer. You can see why I have had a challenge. See my form though. The recordsource is the upcominggames table and the data entry form is for input (ENTER GAME DATA)
-----the answer to this was an update query (a separate form) and then requery the statistics form to show the new matchups that were entered.
As from the comments, this is what I'm thinking of when I read your description:
Since the UpcomingGames will be entered first and exactly one GameResult can be entered per UpcomingGame, this will be a 1:1 relationship. As the name Upcoming says: The Upcoming data has to be entered before the Result can make sense. Unless an UpcomingGame can be cancelled, there will indeed be a Result for the Game, so there is no need to separate the information into 2 tables. I'd say, a user interface could look like this:
As you can see, the T_NUM column is an autovalue. Before entering any data, I initialized that column using a query like this (and deleted that record afterwards):
INSERT INTO Games ( T_NUM )
VALUES (1004);
This way, the numbering started with number 1005.
You won't be able to to avoid gaps in the numbering, as long as the users can remove existing records or cancel the insertion of a new record. If you want at least to avoid the latter, you will need some VBA code in the form.

how to insert if exist update (no unique key)

i have 3 tables (sample),no key restrictions
one is FRUITTABLE, second is FRUITPRICE, third is COMBINATIONS
in FRUITTABLE, we insert what is being sold, color(ie,banana green or yellow),taste,
in FRUITPRICE, we insert how many piece, if applicable pack and the time it was sold
this is how i create combinations
SELECT FT.FRUITS, FT.COLOR, FT.TASTE, COUNT(FP.SALES) AS TOTAL, FP.TIMESOLD
FROM FRUITSTABLE FT
JOIN FRUTSPRICE FP ON FT.ID = FP.ID
WHERE FP.TIMESOLD BETWEEN '2013-12-01 11:00:00' AND '2013-12-01 12:00:00'
GROUP BY FT.FRUITS, FT.COLOR, FT.TASTE
in the COMBINATIONS table, what we do is we group it and count so we will see what is most likely good fruit combination per hour
SO COMBINATIONS WILL OCCUR ONCE EVERY HOUR
lets say
ie: mango,yellow,sour,10, 3:00PM
ie: mango,yellow,sour,12, 4:00PM
ie: mango,yellow,sour,14, 5:00PM
ie: mango,yellow,sour,10, 6:00PM
so evey hour, lets say 3:00PM
we insert
mango,yellow,sour,1, 3:00PM
then another customer bought this combination at the same hour so the data will be
mango,yellow,sour,2, 3:00PM
now, in combinations, we insert it. but if the combination already exist,
i honestly dont know how i can update it..
we need to update it lets say every 5min, maybe i can manage to create SP and EVENT that will
call SP(hoping this is correct)
the only problem is i dont know how to:
select, insert, if exist(the combinations of FT.FRUITS, FT.COLOR, FT.TASTE are same) update
pls let me know if what im thinking is possible or not..
thanks in advance
PS. i already used insert on duplicate key update in some cases
PS. we determine the group combination and total sales(FP.SALES) per hour(TIMESOLD)
EDIT
PS replace into is not applicable as well
also the reason why i cant use a unique key is because it will be useless..
because each combination will occur every hour.. honestly,
i already have solution. but it wont be updated every minute,
my solution will be insert it every hour.
the negative side of doing that is the record in the webpage will not be in real time
all i need to figure out is how i can do something LIKE
insert on duplicate key update (but without using primary key)
so that the table will be updated and the record will be in real time
if its possible to create a workaround
sorry if i have to edit the question many times. i hope this one is constructive.. thank you for your help guys...
You are probably looking for this :
Insert to table or update if exists (MySQL)
OR:
You can actually make the combination (of FT.FRUITS, FT.COLOR, FT.TASTE) a key such that they can individually have multiple values but there will be unique combinations of them in the table.
Creating a Compound Key http://en.wikipedia.org/wiki/Compound_key would be the right solution. However, if you are not able to create keys for whatever reason, do it the other way round:
UPDATE myTable SET [whatever goes here] WHERE FRUITS = [currentFruit] AND COLOR = [currentColor] AND TASTE = [currentTaste]
Now, use your programing language and retrieve the affected row count. If it's 1 - you're done. If it's 0: You need to insert, because there was no row matching your update statement.
Just in case, if you are using load data statement instead of insert(like reading from csv or customized delimited file). You can use the replace flag.
http://dev.mysql.com/doc/refman/5.1/en/load-data.html

swapping values within the same column in mysql during update

My table looks like this,
RangeId CellId Some Coulmns more
101 1
101 2
I ll get a list with [101,2],[101,1] now i have to swap cellId values in the above table. How to write an update query for this. I went through Swapping column values in MySQL but this swaps between two coulmns. Any suggestion..
EDIT: I am swapping the cells in my app and i ll get two cell ids. I have two just swap 2 with 1 and 1 with 2 and rest of the values in the rows remains the same
EDIT2: The table doesnt have any Id column nor a primary key.
With your table as currently stated you cannot really do as you wish as there is no unique way to identify rows. I advise that you step back and look at what you are trying to do as it feels like either a: it's not been thought through, or b: you've not given enough information for this to really be solved
If b:, please provide more information on this table and the tables it links to and precisely what you are trying to achieve (yes I know you want to swap 2 numeric values however without knowing more information about the tables / what can be used to select it is VERY hard to advise accurately)
note below was written for OPs original edit
This isn't a nice way to do it but it may get what you are after, it relies on ID being a PKID
http://sqlfiddle.com/#!2/0c48c/2

Need help on Mysql Database Structure

I have 200 users each user will eventually have a "reviewINFO" table with certain data.
Each user will have a review every 3 to 4 months
So for every review, it creates a new row inside the "reviewINFO" table.
This is where i'm stuck. I'm not sure if I need to serialize a table inside each row or not.
Example:
-> links
"USER1reviewINFO"-row1->USER1table1
-row2->USER1table2
-row3->USER1table3
-row4->USER1table4
-row5->USER1table5
"USER2reviewINFO"-row1->USER2table1
-row2->USER2table2
-row3->USER2table3
-row4->USER2table4
-row5->USER2table5
using this method it will make a couple of thousand rows within two years. And I think its harder to manage.
"Userxtablex" is a table with dynamic rows of children names,ages,boolean
What i'm think of doing is serialize each USERxtable into its corresponding row.
Please help as I would not like to make this complicate or inefficient
Generally, you should never have to serialize data of this nature into a table row to accomplish what your goal is (which I am assuming is an implicit link between a user and a review)
What you need to do is key the reviews by a user_id such that all the reviews are packaged in one table, and relate numerically back to the users table.
Assuming you have an AUTO_INCREMENT primary key in the user table, all you would need is a user_id field in the reviews table that represents what user the review relates to. There is no need for a separate structure for each user, if that's what you are suggesting. Reviews can have date fields as well, so you can perform queries for a specific year or window of time.
You can then use a JOIN query to select out your data set relating to a particular user or review, and apply the usual WHERE clause to determine what result set you want to fetch.

adding data to interrelated tables..easier way?

I am a bit rusty with mysql and trying to jump in again..So sorry if this is too easy of a question.
I basically created a data model that has a table called "Master" with required fields of a name and an IDcode and a then a "Details" table with a foreign key of IDcode.
Now here's where its getting tricky..I am entering:
INSERT INTO Details (Name, UpdateDate) Values (name, updateDate)
I get an error: saying IDcode on details doesn't have a default value..so I add one then it complains that Field 'Master_IDcode' doesn't have a default value
It all makes sense but I'm wondering if there's any easy way to do what I am trying to do. I want to add data into details and if no IDcode exists, I want to add an entry into the master table. The problem is I have to first add the name to the fund Master..wait for a unique ID to be generated(for IDcode) then figure that out and add it to my query when I enter the master data. As you can imagine the queries are going to probably get quite long since I have many tables.
Is there an easier way? where everytime I add something it searches by name if a foreign key exists and if not it adds it on all the tables that its linked to? Is there a standard way people do this? I can't imagine with all the complex databases out there people have not figured out a more easier way.
Sorry if this question doesn't make sense. I can add more information if needed.
p.s. this maybe a different question but I have heard of Django for python and that it helps creates queries..would it help my situation?
Thanks so much in advance :-)
(decided to expand on the comments above and put it into an answer)
I suggest creating a set of staging tables in your database (one for each data set/file).
Then use LOAD DATA INFILE (or insert the rows in batches) into those staging tables.
Make sure you drop indexes before the load, and re-create what you need after the data is loaded.
You can then make a single pass over the staging table to create the missing master records. For example, let's say that one of your staging table contains a country code that should be used as a masterID. You could add the master record by doing something along the lines of:
insert
into master_table(country_code)
select distinct s.country_code
from staging_table s
left join master_table m on(s.country_code = m.country_code)
where m.country_code is null;
Then you can proceed and insert the rows into the "real" tables, knowing that all detail rows references a valid master record.
If you need to get reference information along with the data (such as translating some code) you can do this with a simple join. Also, if you want to filter rows by some other table this is now also very easy.
insert
into real_table_x(
key
,colA
,colB
,colC
,computed_column_not_present_in_staging_table
,understandableCode
)
select x.key
,x.colA
,x.colB
,x.colC
,(x.colA + x.colB) / x.colC
,c.understandableCode
from staging_table_x x
join code_translation c on(x.strange_code = c.strange_code);
This approach is a very efficient one and it scales very nicely. Variations of the above are commonly used in the ETL part of data warehouses to load massive amounts of data.
One caveat with MySQL is that it doesn't support hash joins, which is a join mechanism very suitable to fully join two tables. MySQL uses nested loops instead, which mean that you need to index the join columns very carefully.
InnoDB tables with their clustering feature on the primary key can help to make this a bit more efficient.
One last point. When you have the staging data inside the database, it is easy to add some analysis of the data and put aside "bad" rows in a separate table. You can then inspect the data using SQL instead of wading through csv files in yuor editor.
I don't think there's one-step way to do this.
What I do is issue a
INSERT IGNORE (..) values (..)
to the master table, wich will either create the row if it doesn't exist, or do nothing, and then issue a
SELECT id FROM master where someUniqueAttribute = ..
The other option would be stored procedures/triggers, but they are still pretty new in MySQL and I doubt wether this would help performance.