I have a table with articles and another with the rows in which the articles go
once I delete all articles from a given row I need to delete the row also.
this is my query so far
SET @id = :id;
SET @section = 0;
SET @row = 0;
SET @row_id = 0;
SET @count = 0;
SELECT @row := articles.row_order, @section := articles.section_id
FROM articles
WHERE article.article_id = @id;
DELETE FROM articles WHERE article_id = @id;
SELECT @count := COUNT(articles.article_id)
FROM articles
JOIN rowstyles ON articles.section_id = rowstyles.row_section_id
AND articles.row_order = rowstyles.row_position
WHERE rowstyles.row_section_id = @section AND rowstyles.row_position = @row;
DELETE ...
How do I delete the row (rowstyles) ONLY IF @count is 0 (zero)
You can add the count to the DELETE
s where clause:
-- Delete rowstyles with no article
DELETE FROM rowstyles WHERE (SELECT COUNT(a.id) FROM articles a WHERE a.section_id = rowstyles.row_section_id) = 0;
Note that this will delete all the rowstyles with no articles. If it's only for the given section you can add to the WHERE clause:
DELETE FROM rowstyles
WHERE (
SELECT COUNT(a.article_id)
FROM articles a
WHERE a.section_id = @section
AND a.row_order = @row
) = 0
AND rowstyles.row_section_id = @section
AND rowstyles.row_position = @row;
Before running SQL you found on the internet please make sure you have a backup.