Guide to inserting data into mariadb only if the entry does not already exist

I am faced with the challenge of avoiding duplicate entries in a table that contains ID, title, and userid fields. Currently, I have implemented logic to store view history in the database when certain media is viewed.

However, despite my efforts, duplicate entries are still occurring even after trying the following code:

    dataAccessor.viewers = {
  add: ({ courseId, viewerOid }) => {
    const query =
      "IF NOT EXISTS (SELECT * FROM course_video_viewers WHERE course_id = ? AND WHERE azure_oid = ?) INSERT INTO course_video_viewers (course_id, azure_oid) VALUES (?, ?)";

    const inputs = [courseId, viewerOid];

    return sendQueryAndReturnResultsAsPromise(query, inputs);
  }
};

Answer №1

To avoid duplicate entries, consider adding a unique index on course_id and azure_oid. This will prevent the same data from being inserted multiple times. You can then use the SQL command

INSERT IGNORE INTO course_video_viewers...
to handle inserting records efficiently by dropping and reinserting if necessary.

Answer №2

To ensure uniqueness in the table, it is recommended to add a unique constraint for both the course_id and azure_oid columns:

ALTER TABLE course_video_viewers 
ADD CONSTRAINT unique_constraint_video_view 
UNIQUE (course_id, azure_oid);

If modifying the table's definition is not an option, you can achieve the same result using an INSERT ... SELECT statement:

INSERT INTO course_video_viewers (course_id, azure_oid) 
SELECT ?, ?
FROM dual
WHERE NOT EXISTS (SELECT * FROM course_video_viewers WHERE course_id = ? AND WHERE azure_oid = ?)

The use of FROM dual may be omitted for MySql versions 5.7 and above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: An unexpected 'if' token was not caught

Encountering an error related to the question title while working with this code snippet: $LAB.queue(function setup() { FB.init({ appId: '00000000', status: true, cookie: true, xfbml: true, logging: &ap ...

What is the most efficient way to transform HTML into React components effortlessly?

I have been attempting to automate the process of converting HTML into React components. I followed the link below to automatically convert HTML into React components: https://www.npmjs.com/package/html-to-react-components However, I encountered an issue ...

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

Switch out multiline text with javascript

Could someone assist me with this question? I am attempting to locate and replace specific code within a JavaScript file. The code is included in an AJAX response that contains a significant amount of HTML code. After retrieving the AJAX response, I stor ...

Tips for utilizing props in a Vue component

When trying to incorporate a prop into a computed value, I encounter the following error: [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" found in ---> at src/cmps/space-details/space-imgs.vue at src/pa ...

Is there a method to send a function through a remix loader function?

I'm currently attempting to pass a function as one of the values from a remix route loader function export const loader: LoaderFunction = async ({ request }) => { const userId = await requireUserId(request) const user = await getUserById(userId ...

Currently, I am experimenting with creating interactive tabs by utilizing jQuery

Does anyone have suggestions on how to create clickable tags using JavaScript without causing everything to disappear when clicking on the tabs? Here is the HTML code: <div id="contentwrap" class="round"> <h1>About Eclipse</h1> ...

Prevent expand/collapse action on list item checkbox in jQuery Mobile

I'm trying to create a listview item with a collapsible format and a checkbox for selecting/unselecting the item. However, when I click on the checkbox, it ends up expanding/collapsing the container instead. Does anyone have any ideas on how to preve ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...

Has anyone successfully utilized pgloader for transferring data from Mysql to Postgres during a migration process?

After using yum install on CentOS 6.5, I successfully installed pgloader. However, I am encountering an issue when trying to load a specific file using the command pgloader mysql.load. LOAD DATABASE from mysql://root:<a href="/cdn-cgi/l/email-pr ...

What are the steps for translating multiple meshes in various directions using three.js?

One issue that I am encountering involves creating 100 meshes with a for loop, all of which have the same position coordinates of 0,0,0. I would like these meshes to move in different directions individually. Below is my code for creating the 100 meshes: ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

What could be causing the lack of change in a dynamic input value in Angularjs?

There is an input with ng-model="articleTitle" and a div with {{articleTitle. When the input is typed in, the div is updated. However, there is a box that lists all articles enclosed by <div class="element">...</div>. When a list div is clicke ...

The communication issue between the two devices has occurred due to a missing shared object file, specifically, the libmariadb.so.3 file cannot be opened

I have set up two separate devices to function as my MySql server and Django server. While my system works perfectly on my development device, it encounters issues when I try to switch to the other designated devices. The settings for the server located at ...

Arranging an array of objects in Javascript based on the first attribute, and in cases of equality, sorting with another attribute

I have an array structured like this: let myarr = [{id:1 , name: "mark" , birthday: "1990-08-18"}, {id:2 , name: "fred" , birthday: "1990-08-17"}, {id:3 , name: "franck" , birthday: "1990-08-16"}, ...

Using Mongoose to Add Documents

Showing off my Mongoose schema: let DiscountSchema = new Schema({ deal:{ discountid:{ type: String, require: true, unique: true, }, title: String, }, // Embedded sub-section deta ...

Click on the entire Material-UI formControlLabel to select it, not just the text

I have recently started working with the material UI. Currently, I am dealing with a form that looks like this: <FormControl variant="outlined" className={css.formControl} margin="dense" key={"abc_" + index} > <FormControlLabel cont ...

Creating a file solely for route definitions and then employing them within index.js

My index.js file contains the following routes: import { createRouter, createWebHistory } from '@ionic/vue-router'; import { RouteRecordRaw } from 'vue-router'; const routes = [{ path: '', redirect ...

Ways to identify individuals who have visited a website on multiple occasions within a 60-day timeframe starting from their initial visit

I attempted to create a SQL query using a self-join but I seem to be missing something: SELECT a.user_id, a.visit_dt FROM dataset1 a JOIN dataset1 b ON a.user_id = b.user_id AND abs(datediff(day, a.visit_dt, b.visit_dt)) < ...

Using V-For with data fetched from an axios request: A step-by-step guide

How can I dynamically populate V-Cards after making an Axios request to retrieve data? The Axios request is successful, but the v-for loop does not populate with V-Cards. I've also attempted to make the request before the rendering is completed (usin ...