简体   繁体   中英

SQL - Delete row based on number of rows in another table

How would I go about deleting a row from the table 'subjects' that has a primary id 'subject_id' based on the number of rows in another table named 'replies' that uses a 'subject_id' column as a reference.

Example in pseudo code: If ('subject' has less than 1 reply){ delete 'subject'}

I don't know much about SQL triggers so I have no clue if I would be able to incorporate this directly in the database or if I'd have to write some PHP code to handle this...

To delete any subjects that have had no replies, this query should do the trick:

DELETE s.* FROM subjects AS s
WHERE NOT EXISTS 
    (
    SELECT r.subject_id
    FROM replies AS r
    WHERE r.subject_id = s.subject_id
    );

Demo: DB Fiddle Example

One of the MySQL gurus will need to weigh in on whether or not you can do this directly, but in PHP you could...

$query = "SELECT subject_id FROM subjects WHERE subject='test'";
$return = mysqli_query($mysqli, $query);
$id = mysqli_fetch_assoc($return);

$query = "SELECT reply_id FROM replies WHERE subject_id='".$id[0]."'";
$return = mysqli_query($mysqli, $query);

if(mysqli_num_rows($return) < 1){
    $query = "DELETE FROM subjects WHERE subject_id='1'";
    $return = mysqli_query($mysqli, $query);
}

This example assumes the "subject" is unique. In other words, SELECTing WHERE subject='test' will only ever return one subject_id. If you were doing this as a periodic cleaning, you would grab all the subject_id values (no WHERE clause) and loop through them to remove them if no replies.

You can achieve this in one query by selecting all (unique) subject-ids from the replies table, and delete all subjects that doesn't have a reply in there. Using SELECT DISTINCT , you don't get the IDs more than once (if a subject has more than one reply), so you don't get unnecessary data.

DELETE FROM subjects 
WHERE subject_id NOT IN (SELECT DISTINCT subject_id FROM replies)

Any subject that doesn't have a reply should be deleted!

So you want to delete all subjects with no replies:

DELETE FROM subjects WHERE subject_id NOT IN 
(SELECT subject_id FROM replies);

I think this is what you want...

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