简体   繁体   中英

Is there better way to do this query?

SELECT *
FROM a
WHERE a.re_id = 3443499
AND a.id IN 
(
   SELECT b.rsp_id FROM b
   WHERE b.f_id = 9
   GROUP BY b.rsp_id
   HAVING FIND_IN_SET(16, GROUP_CONCAT(b.o_id)) > 0
   AND FIND_IN_SET(15, GROUP_CONCAT(b.o_id)) > 0

   UNION

   SELECT b.rsp_id FROM b
   WHERE b.f_id = 4
   GROUP BY b.rsp_id
   HAVING FIND_IN_SET(5, GROUP_CONCAT(b.o_id)) > 0
)
ORDER BY id DESC

Here "f_id" is array and its values are those in first parameter of "FIND_IN_SET" function. For example

9=>(
 16,
 15
),
4=>(
 5
)

Sample data for those 2 folumns in table b, 2 columns f_id and o_id

f_id o_id
9    15
9    18
9    23
4    5
3    8

The gist of this answer is that the current query does not run. So, fix the syntax and ask another question.

First, you could write the query so it is syntactically correct. The query will fail as written, because the first subquery returns at least two rows and the second only one.

Second, use UNION ALL instead of UNION , unless you specifically want to incur the overhead of removing duplicates.

Third, the ORDER BY will generate an error.

Fourth, the GROUP_CONCAT() is dangerous and unnecessary.

I'm not 100% sure this is the intention, but I would start with a query like this:

SELECT a.id, a.re_id
FROM a
WHERE a.re_id = 3443499 AND
      a.id IN (SELECT b.rsp_id
               FROM b
               WHERE b.f_id = 9
               GROUP BY b.rsp_id
               HAVING MAX(b.o_id = 16) > 0 AND
                      MAX(b.o_id = 15) > 0
              )
UNION ALL
SELECT b.rsp_id, NULL
FROM b
WHERE b.f_id = 4
GROUP BY b.rsp_id
HAVING MAX(b.o_id = 5) > 0
ORDER BY id;

Then, if you want this optimized, I would suggest asking another question, along with relevant information about the table structures and current performance.

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