English 中文(简体)
MySQL:连接两个表,随机选择一行
原标题:MySQL: Join two tables, select one row at random

首先,我创建了一个屏幕演员阵容,以解释我拥有什么以及我试图创建什么。更容易理解。

请在此处查看屏幕投影:http://www.youtube.com/v/lZf3S3EGHDw?fs=1&;hl=en_US&;rel=0&;hd=1

表格:

CREATE TABLE `locations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(45) DEFAULT NULL,
  `latitude` decimal(10,6) DEFAULT NULL,
  `longitude` decimal(10,6) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO `locations` (`id`,`title`,`latitude`,`longitude`)
VALUES
    (1, Randall Automotive Car Repair ,42.729642,-84.515524),
    (2, Belle Tire ,42.662458,-84.538177),
    (3, Better Buy Muffler & Breaks ,42.740845,-84.589541),
    (4, Kwik Car Wash ,42.721221,-84.545926);


CREATE TABLE `listings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `token` varchar(4) DEFAULT NULL,
  `location` varchar(45) DEFAULT NULL,
  `info` varchar(70) DEFAULT NULL,
  `status` varchar(45) DEFAULT NULL,
  `auto_inactive` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


INSERT INTO `listings` (`id`,`token`,`location`,`info`,`status`,`auto_inactive`)
VALUES
    (35, 4uaJ , 1 , All employees are NSA certified. , active , 0 ),
    (36, RdcX , 1 , Family Owned and Operated , active , 0 ),
    (37, WuaZ , 1 , Also repair Small engines , active , 0 ),
    (38, 2jxD , 2 , Open on the weekends. , active , 0 ),
    (39, Xsu4 , 2 , Two locations in this town. , active , 0 ),
    (40, p9cB , 2 , Advertise on Tiger s Baseball , active , 0 ),
    (41, mYa3 , 2 , Started right here in Michigan , active , 0 ),
    (42, Q8g5 , 3 , Building built in 1997 , active , 0 ),
    (43, l734 , 3 , Great ratings from BBB , active , 0 ),
    (44, 7cLY , 4 , Open in the Winter , active , 0 ),
    (45, gtlU , 4 , Largest car wash in town , active , 0 ),
    (46, fEjK , 4 , Owned and Operated by John Smith , active , 1285614174 ),
    (47, dRcu , 4 , Opened in 1987 , inactive , 0 );



<?php

include_once( include.php ); // Calls the Mysql Database`
ini_set( date.timezone ,  America/Detroit );


$user_latitude = 42.7160084;
$user_longitude = -84.5615018;


$sql =  mysqli_query($mysqli, "SELECT 
                                        loc.id, 
                                        loc.title, 
                                        ( 3959 * acos( cos( radians( ".$user_latitude." ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians( ".$user_longitude." ) ) + sin( radians( ".$user_latitude." ) ) * sin( radians( latitude ) ) ) ) AS distance

                                FROM 
                                        locations loc 

                                WHERE EXISTS(SELECT NULL FROM listings li
                                        WHERE li.location = loc.id 
                                        AND li.status =  active  
                                        AND (li.auto_inactive >  ".time()."  OR li.auto_inactive =  0 )) 

                                ORDER BY distance");


while($locations = mysqli_fetch_array($sql)) {

        $listings = mysqli_fetch_array(mysqli_query($mysqli, "SELECT listings.token, listings.info FROM listings WHERE (listings.location =  ".$locations[ id ]." ) AND listings.status =  active  AND (listings.auto_inactive >  ".time()."  OR listings.auto_inactive =  0 ) ORDER BY RAND()"));


        echo  <a href="listing.php?id= .$listings[ token ]. "><h2> .$locations[ title ]. </h2></a> ;

        echo  <h5>Distance:  .sprintf ( %.2f , $locations[ distance ]).  mi</h5> ;
        echo  <p> .$listings[ info ]. </p> ;
        echo  <hr/> ;
}

?>

如果你需要澄清什么,请告诉我。非常感谢。

最佳回答

这个有效:

SELECT t1.title, t2.token, t2.info
    FROM
        (SELECT loc.id AS id, loc.title AS title,( 3959 * acos( cos( radians( ".$user_latitude." ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians( ".$user_longitude." ) ) + sin( radians( ".$user_latitude." ) ) * sin( radians( latitude ) ) ) ) AS distance
            FROM locations loc
            WHERE EXISTS(SELECT NULL FROM listings li
                    WHERE li.location = loc.id
                        AND li.status =  active 
                        AND (li.auto_inactive > UNIX_TIMESTAMP() OR li.auto_inactive =  0 ))
        ) t1
    JOIN
        (SELECT DISTINCT(listings.location) AS location, listings.token AS token, listings.info AS info
            FROM listings
            WHERE listings.status =  active 
                AND (listings.auto_inactive > UNIX_TIMESTAMP() OR listings.auto_inactive =  0 )
            ORDER BY RAND()
        ) t2
    ON t1.id=t2.location
        GROUP BY t2.location
        ORDER BY t2.location ASC;

我还建议更改列表表,使位置状态auto_inactive列类型为int-对它们使用varchar没有意义。

问题回答

我不知道它的性能如何,甚至不知道它是否能工作,但似乎你可以加入一个子查询,并根据rand限制/排序。我发现了这个这里的问题/答案我是基于这个。试试这样的东西:

SELECT 
    loc.id, 
    loc.title, 
    ( 3959 * acos( cos( radians( ".$user_latitude." ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians( ".$user_longitude." ) ) + sin( radians( ".$user_latitude." ) ) * sin( radians( latitude ) ) ) ) AS distance,
    listings.token,
    listings.info
FROM
    locations loc
JOIN
    (SELECT
             location,
             token,
             info
         FROM listings
         WHERE (listings.location=loc.id)
             AND status =  active 
             AND (auto_inactive >  ".time()."  OR listings.auto_inactive =  0 )
         ORDER BY RAND() LIMIT 1) listings
     ON listings.location=loc.id
ORDER BY distance

edit:此外,如果这真的有效,联接将把位置限制在只有列表的位置,这样你就不需要检查了。





相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签