简体   繁体   中英

IF EXISTS clause Local SQL

The code below all works fine. However, I would like to know how to know how to ensure that a 'late' entry is only added to the lates table if a student by that name already exists in the student table. I tried several versions of 'IF EXISTS' and 'WHERE EXISTS' but can't seem to get the syntax correct. I would also like to return a javascript error if the name does not exist in the student table. The desired change is in the addLate function.

    <fieldset>
        <legend><b>Details</b></legend>
        <label>First Name </label><input id = "firstname" type="text" autofocus="" placeholder="Enter first name"><br><br>
        <label>Last Name </label><input id = "lastname" type="text" autofocus="" placeholder="Enter last name"><br><br>
    </fieldset>

    <fieldset>
        <legend><b>Information</b></legend>
        <label> Current date:</label>
        <input type="text" id="datelate"/><br><br>
        <label> Detention date:</label>
        <input id = "detentiondate" type="date" ><br><br>
        <label>Time</label>
            <select id="mora">
                <option value="AM">Morning</option>
                <option value="PM">Afternoon</option>
            </select>
        <br> <br>
        <label> Reason:</label>
        <textarea id = "reason" rows="2" cols="60"></textarea><br><br>
    </fieldset>

    <br>
    <input type="reset" value="Reset">

    <button type="button" id="addlate" onclick="addLate();">Add late</button>

    </body>

<script>

if (window.openDatabase) {
    var mydb = openDatabase("students2_db", "0.1", "A Database of Students", 1024 * 1024);

    mydb.transaction(function (t) {
         t.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY ASC, fname TEXT, lname TEXT, mclass TEXT, aclass TEXT, com TEXT, lates INTEGER DEFAULT 0)");
        t.executeSql("CREATE TABLE IF NOT EXISTS lates (lid INTEGER PRIMARY KEY ASC, flname TEXT, llname TEXT, time TEXT, reason TEXT, date TEXT, nextdet TEXT)");
    });

} else {
    alert("WebSQL is not supported by your browser!");
}

function ClearFunction() {
    document.getElementById("mora").value = "";
}

function DateFunction() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();

    if(dd<10) {
        dd='0'+dd
    } 

    if(mm<10) {
        mm='0'+mm
    } 

    today = dd+'-'+mm+'-'+yyyy;
    document.getElementById('datelate').value= today;
}

function addLate() {

    if (mydb) {

        var flname = document.getElementById("firstname").value;
        var llname = document.getElementById("lastname").value;
        var date = document.getElementById("datelate").value;
        var nextdet = document.getElementById("detentiondate").value;
        var time = document.getElementById("mora").value;
        var reason = document.getElementById("reason").value;

        if (flname !== "" && date !== "" && nextdet !== "" && llname !== "" && reason !== "" && time !== "") {

            mydb.transaction(function (t) {
                t.executeSql("INSERT INTO lates (flname,llname,time,reason,date,nextdet) VALUES (?,?,?,?,?,?)" , [flname,llname,time,reason,date,nextdet]);
                t.executeSql("UPDATE student SET lates = lates + 1 WHERE lname =? ", [llname]);
                alert("Entry succesfully added");
                document.getElementById("firstname").value = "";
                document.getElementById("lastname").value = "";
                document.getElementById("detentiondate").value = "";
                document.getElementById("reason").value = "";
            });
        } else {
            alert("You must fill out all the empty information!");
        }
    } else {
        alert("db not found, your browser does not support web sql!");
    }
}


</script>

You can use a simple SELECT query using student id to check if a student is within the student database, then you use count of rows returned to determine if the student exists. If rows returned > 0, then your student exists, else, student does not exist.

Something like this:

SELECT id
FROM student
WHERE id = 'student's id'

The best way to implement this is by adding a foreign key constraint on the lates table such that the database considers it an error to insert a row into lates if there is not a corresponding entry in students .

In your case this is complicated by the fact that you have not normalized your tables properly. In database design it is consider bad form to have the same information included in mutliple tables: so instead of repeating the first and last name of each student in the lates table, you only need to include information that is specific to that table and reference everything else back to the students table.

So, I would make your lates table look like this:

CREATE TABLE IF NOT EXISTS lates (
    lid INTEGER PRIMARY KEY ASC,
    student_id INTEGER REFERENCES student(id)
    time TEXT, 
    reason TEXT, 
    date TEXT, 
    nextdet TEXT
)

Note that instead of fname and lname being directly included in this table, you have student_id which is a foreign key reference to the id column of the student table. Now you will automatically get an error if you try to insert a student_id into the lates table if it does not exist in the students table.

You might be wondering how to display the information in the lates table while showing the actual names of the students - this is done via a join:

SELECT fname,
       lname,
       time,
       reason
FROM lates
    LEFT JOIN students ON lates.student_id=student.id;

By the way, I assume you know that web databases are deprecated so it is probably not a good idea to use them for any real project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM