I am not to savvy on SQL queries but I am trying to build a query to remove any data (reported comments) based on a join to another table (user) using an ID to match, here is a sample schema below:
create table tbl_reported_comment(id int, commentId int, reported_by_userid int);
insert tbl_reported_comment values
(1, 1, 101),
(2, 2, 131),
(3, 3, 101),
(4, 4, 101),
(5, 5, 24),
(6, 6, 201),
(7, 7, 1),
(8, 8, 24),
(9, 9, 23),
(10, 10, 16),
(11, 11, 31);
Create table tbl_user(userId int, Username varchar(50));
insert tbl_user values
(1, 'admin'),
(101, 'test1'),
(131, 'test2'),
(24, 'test3'),
(201, 'test4');
What I am trying to achieve in this instance is the following:
Remove any data in the tbl_reported_comment table where the
[reported_by_userid] column doesn’t exist as an [userId] in the user
table
Here is a link to the SQLFIDDLE with this sample schema: SQLFiDDLE. I am using SQL Server as the database.
Many thanks,
How about this?
This will delete those rows and it will output those rows it deleted to the screen (in SQL Server Management Studio) so you can see what was deleted.
And Ben is right – once you’ve done this, you should establish a foreign key relationship between those two tables to avoid zombie data like this in the future!