如何在子查询中进行内部连接? MySQL的

时间:2017-04-14 06:32:35

标签: mysql

我正在尝试将此select语句调整到我的表中。此查询从邮政编码表中选择所有邮政编码,这些邮政编码位于给定邮政编码的特定距离内。但是,我有一个沙龙表,将邮政编码存储为邮政编码表中的外国邮政编码。我需要在给定邮政编码的特定距离内选择所有沙龙。

DELIMITER //
    CREATE PROCEDURE zip_search(lat_param FLOAT(9,6),
     long_param FLOAT(9,6), dist_param INT(100)
    )
    BEGIN
    SELECT zipcode
      FROM (
     SELECT z.zipcode, z.latitude, z.longitude,
            p.radius,
            p.distance_unit
                     * DEGREES(ACOS(COS(RADIANS(p.latpoint))
                     * COS(RADIANS(z.latitude))
                     * COS(RADIANS(p.longpoint - z.longitude))
                     + SIN(RADIANS(p.latpoint))
                     * SIN(RADIANS(z.latitude)))) AS distance
      FROM accounts_zip AS z
      JOIN (   /* these are the query parameters */
            SELECT  lat_param  AS latpoint,  long_param AS longpoint,
                    dist_param AS radius,      69.0 AS distance_unit
        ) AS p ON 1=1
      WHERE z.latitude
         BETWEEN p.latpoint  - (p.radius / p.distance_unit)
             AND p.latpoint  + (p.radius / p.distance_unit)
        AND z.longitude
         BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
             AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
     ) AS d
     WHERE distance <= radius
     ORDER BY distance;
    END //

我从沙龙表中选择后尝试添加内连接,但是我不理解子查询和连接非常好。任何想法将不胜感激。

DELIMITER //
        CREATE PROCEDURE zip_search(lat_param FLOAT(9,6),
         long_param FLOAT(9,6), dist_param INT(100)
        )
        BEGIN
        SELECT *
          FROM (
         SELECT z.zipcode, z.latitude, z.longitude,
                p.radius,
                p.distance_unit
                         * DEGREES(ACOS(COS(RADIANS(p.latpoint))
                         * COS(RADIANS(z.latitude))
                         * COS(RADIANS(p.longpoint - z.longitude))
                         + SIN(RADIANS(p.latpoint))
                         * SIN(RADIANS(z.latitude)))) AS distance
          FROM accounts_salon INNER JOIN accounts_zip ON accounts_salon.id=accounts_zip.id AS z
          JOIN (   /* these are the query parameters */
                SELECT  lat_param  AS latpoint,  long_param AS longpoint,
                        dist_param AS radius,      69.0 AS distance_unit
            ) AS p ON 1=1
          WHERE z.latitude
             BETWEEN p.latpoint  - (p.radius / p.distance_unit)
                 AND p.latpoint  + (p.radius / p.distance_unit)
            AND z.longitude
             BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
                 AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
         ) AS d
         WHERE distance <= radius
         ORDER BY distance;
        END //

1 个答案:

答案 0 :(得分:-1)

我不认为第一个内连接中的'AS z'是必要的,如果你试图得到表accounts_salon和accounts_zip的连接结果,并把它当作第二个内连接的左表,那么就继续写下一个内部联接。