I
I
Igor2019-12-01 20:17:12
MySQL
Igor, 2019-12-01 20:17:12

How to combine parameters in native query?

Colleagues, the most stupid question!
Share the practice of combining query parameters.
Regarding nativeness, I'm trying to make the most optimal query.
What do I want to receive?
Number of companies, according to the specified
SQL parameters
This query, surprisingly, calculates as quickly as possible.

EXPLAIN 

SELECT         COUNT(o.id) 
FROM           organizations o 
LEFT JOIN      organizations_categories oc ON o.id = oc.organization_id AND oc.category_id = 9
WHERE o.id     IN (
      SELECT   f.organization_id 
      FROM     features f 
      WHERE    f.name = (
                     SELECT   f2.name 
                     FROM     features f2 
                     WHERE    f2.id = 5685427
                     ) 
                 ) 
AND  o.city_id = 5128 AND oc.category_id = 9

5de3f659bd9d2706856272.png
Tables that participate in the query
-------------------------------------- --------------
- organizations: rows count 5,000,000
- organizations_category: rows count 7,000,000
- features: rows count ~7,000,000
----------- ------------------------------------------------------
Here is an example:
(Blank)
0 - means the parameter is not passed and should not be included in the request.
/**
     * @param string $q
     * @param int $city_id
     * @param int $category_id
     * @param int $feature_id
     * @return void
     * @throws NonUniqueResultException
     */
    public function getCount($q = "", int $city_id = 0, int $category_id = 0, int $feature_id = 0)
    {
        $rsm = new ResultSetMapping;
        $rsm->addScalarResult('COUNT(o.id)', 'total');

        $query = $this->getEntityManager()->createNativeQuery("
            SELECT         COUNT(o.id) 
            FROM           organizations o 
            LEFT JOIN      organizations_categories oc ON o.id = oc.organization_id AND oc.category_id = 9
            WHERE o.id     IN (
                SELECT          f.organization_id 
                FROM            features f 
                WHERE           f.name = (
                    SELECT          f2.name 
                    FROM            features f2 
                    WHERE           f2.id = 5685427
                                ) 
                            ) 
            AND  o.city_id = 5128 AND oc.category_id = 9
        ", $rsm);


        return $query->getSingleScalarResult();
    }

Or maybe there is an option using a builder?
Yes, I tried, but it collects the request according to its own rules, and often these requests can take 5 minutes to complete.
Yes, I can set up crutches, everything will work.
I want beautiful.
Share your practice.
Thank you!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question