Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MINUS operator in MySQL?

Tags:

php

mysql

I have some tables where I am getting the emails. And I don't want to get the emails in table tbl_unsubscribe. I wrote the query like :

SELECT cand_email FROM tbl_cand_data
UNION
SELECT emp_email FROM tbl_emp_data
UNION
SELECT email FROM tbl_uptade_list
UNION
SELECT feed_email FROM tbl_feedback
UNION
SELECT admin_email FROM tbl_admin_emails    

But I am getting a syntax error. Is the MINUS operator not valid for MySQL ?

like image 443
AssamGuy Avatar asked Dec 05 '11 13:12

AssamGuy


People also ask

Does MySQL have MINUS operator?

Unfortunately, MySQL does not support MINUS operator. However, you can use join to emulate it. In this tutorial, you have learned about the SQL MINUS operator and how to emulate MINUS operator in MySQL using LEFT JOIN clause.

What is MINUS operator in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

How do you put MINUS in SQL?

To use the MINUS operator, you write individual SELECT statements and place the MINUS operator between them. The MINUS operator returns the unique rows produced by the first query but not by the second one.

What is the use of MINUS query?

A Minus Query is a query that uses the MINUS operator in SQL to subtract one result set from another result set to evaluate the result set difference. If there is no difference, there is no remaining result set. If there is a difference, the resulting rows will be displayed.


2 Answers

A NOT IN() subquery can be used here, since MySQL doesn't support MINUS.

SELECT 
  cand_email
FROM tbl_cand_data 
WHERE can_email NOT IN (SELECT un_email FROM tbl_unsubscribe)

It can also be done with a LEFT JOIN, looking for NULLs in the un_email column:

SELECT cand_email 
FROM
   tbl_cand_data
   LEFT JOIN tbl_unsubscribe ON tbl_cand_data.can_email = tbl_unsubscribe.un_email
WHERE tbl_unsubscribe.un_email IS NULL

To exclude them from a bunch of UNION operations, wrap the UNION group in () as a subquery:

SELECT email FROM (
  SELECT cand_email AS email FROM tbl_cand_data
  UNION
  SELECT emp_email AS email FROM tbl_emp_data
  UNION
  SELECT email FROM AS email tbl_uptade_list
  UNION
  SELECT feed_email AS email FROM tbl_feedback
  UNION
  SELECT admin_email AS email FROM tbl_admin_emails
) email_list
WHERE email NOT IN (SELECT un_email FROM tbl_unsubscribe)
like image 174
Michael Berkowski Avatar answered Sep 21 '22 13:09

Michael Berkowski


Unfortunately MINUS and INTERSECT are not supported by MySQL, but you can get the same result using JOIN for MINUS, UNION for INTERSECT.

SELECT cand_email FROM tbl_cand_data
LEFT JOIN tbl_unsubscribe ON (cand_email = un_email)
WHERE un_email IS NULL
like image 24
Maxim Krizhanovsky Avatar answered Sep 25 '22 13:09

Maxim Krizhanovsky