简体   繁体   中英

How to get the intersection of 2 mysql queries?

Suppose I have a MySQL table which looks like this:

在此处输入图片说明

Each job in the table contains 3 tasks.

How can I get all the JobId s whose taskA is in Done state and taskB is in New state?

In my case, I want a query which returns qwert , and zxcv .

I've come up with this query:

select JobId from MyTable where TaskSeq=0 and TaskState='Done'
intersect
select JobId from MyTable where TaskSeq=1 and TaskState='New';

but my version of MySQL doesn't support the intercept operator.

My ultimate goal is to write the query in sequelize . But I think I should know the MySQL query first so that I can create a sequlize query.

And I also wish that the sequlize query can be done in 1 function instead of multiple functions concatenated with then .

Here's the SQL Fiddle to help you try the table.

You could just use a join:

select mt.JobId 
from   MyTable mt
         join MyTable mt2 on mt2.JobId = mt.JobId
where  mt.TaskSeq = 0 and mt.TaskState = 'Done' and mt2.TaskSeq = 1 and mt2.TaskState = 'New'

Here's an attempt at Sequelize on this query, however this is a guess. Hopefully it gives you something to work with:

MyTable.findAll({
    attributes: ['JobId', 'TaskSeq', 'TaskState'],
    include: [{
        model: MyTable,
        attributes: ['JobId', 'TaskSeq', 'TaskState'],
        where: { 
            JobId: Sequelize.col('MyTable.JobId'),
            TaskSeq: 1,
            TaskState: 'New'
        }
    }],
    where {
        TaskSeq: 0,
        TaskState: 'Done'
    }
});

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