简体   繁体   中英

Mysql Query has me at a loss

New Post I ended up avoiding that query entirely. I just couldn't get the results I was looking for. To get the desired results, I came up with this...

Also, if you guys come up with that query, I'd really look to remove this work around.

Thanks for all the help so far!

function get_converstations($data)
{  
    //get possible senders into an array
    $sender_sql = "SELECT DISTINCT `users`.`aid` AS `aid`, `users`.`nickname` AS `nickname`
                FROM `users`,`messages` 
                WHERE  `messages`.`sender` =  '".$data['aid']."'
                AND `messages`.`recipient` = `users`.`aid`";
    $query = mysql_query($sender_sql);
    if(mysql_num_rows($query) > 0)
    {   
        $sender_data = array();
        while ($row = mysql_fetch_array($query)){
                $sender_data[$row['aid']] = $row['nickname'];
        }
    }           


    //get possible recipients into an array         
    $recipient_sql = "SELECT DISTINCT `users`.`aid`, `users`.`nickname` 
                FROM `users`,`messages` 
                WHERE  `messages`.`recipient` =  '".$data['aid']."'
                AND `messages`.`sender` = `users`.`aid`";                   
    $query = mysql_query($recipient_sql);
    if(mysql_num_rows($query) > 0)
    {
        while ($row = mysql_fetch_array($query)){
                $recipient_data[$row['aid']] = $row['nickname'];
        }
    }       

    //merge the arrays to overrite any duplicate people.
    $no_keys_persons = array_merge($sender_data, $recipient_data);

    //create a new array with keys
    foreach($no_keys_persons as $aid => $nickname)
    {
        $persons[] = array(
            "aid" => $aid,
            "nickname" => $nickname
        );
    }

    //print_r($persons);
    //create the conversations array
    foreach($persons as $person)
    {
        $sql = "SELECT * FROM `messages` WHERE `sender` = '".$data['aid']."' AND `recipient` = '".$person['aid']."' OR `sender` = '".$person['aid']."' AND `recipient` = '".$data['aid']."' ORDER BY `id` DESC LIMIT 1";
        $query = mysql_query($sql);
        if(mysql_num_rows($query) > 0)
        {
            while($row = mysql_fetch_array($query))
            {
                $conversations[] = array(
                    "person_aid" => $person['aid'],
                    "person_nickname" => $person['nickname'],
                    "sender" => $row['sender'],
                    "recipient" => $row['recipient'],
                    "body" => $row['body'],
                    "timestamp" => $row['timestamp'],
                    "ip" => $row['ip']
                );
            }
        }

    }

    //print_r($conversations);                              
    return $conversations;

}

Then when I call that function on my controller..

//create the data array from url
$data = array(
    "aid" => $_GET['aid'],
    "nickname" => $_GET['nickname'],
    "ip" => $_SERVER['REMOTE_HOST'],
);

//instantiate any classes
include 'db.php';
include 'messages_model.php';
$messages = new messages_model();

$coversations = $messages->get_converstations($data);

foreach ($coversations as $conversation)
{
    echo '&conversation=';
    echo '&sender='.$conversation['sender'];
    if($conversation['sender'] === $data['aid']) { echo '&sender_nickname='.$data['nickname']; } else { echo '&sender_nickname='.$conversation['person_nickname']; }
    echo '&recipient='.$conversation['recipient'];
    if($conversation['recipient'] === $data['aid']) { echo '&recipient_nickname='.$data['nickname']; } else { echo '&recipient_nickname='.$conversation['person_nickname']; }
    echo '&body='.$conversation['body'];
    echo '&timestamp='.$conversation['timestamp'];

}

Original Post I am at a loss here guys. Please see if you can help me put this query together.

I have a table called messages.

    CREATE TABLE  `db.app`.`messages` (
    `id` INT( 32 ) NOT NULL AUTO_INCREMENT ,
    `sender` VARCHAR( 64 ) NOT NULL ,
    `recipient` VARCHAR( 64 ) NOT NULL ,
    `body` TEXT NOT NULL ,
    `timestamp` INT( 32 ) NOT NULL ,
    PRIMARY KEY (  `id` )
    ) ENGINE = MYISAM ;

And a table called users.

    CREATE TABLE  `db.app`.`users` (
    `id` INT( 32 ) NOT NULL AUTO_INCREMENT ,
    `nickname` VARCHAR( 64 ) NOT NULL ,
    PRIMARY KEY (  `id` )
    ) ENGINE = MYISAM ;

When a message is made, it inserts the ID of the sender into messages . sender , the ID of the recipient into messages . recipient , the message body, and UNIX timestamp. This is working fine.

My problem lies with getting a list of all the unique conversations. (Like text messages on iPhones).

so if we have data like so...

messages table;   
 id  | sender | recipient | body | timestamp  
 1   | 1234 | 5678 | testing message | 1290233086  
 2   | 5678 | 1234 | testing reply | 1290233089  

users table;  
 id | nickname   
 1234 | john  
 5678 | peter  

I would like to be able to generate query results like so...

results;  
 other_person_id | other_person_nickname | last_message  | last_message_timestamp  
 1234            | john                  | testing reply | 1290233089  

For the life of me, I cant figure out this query....

This is a job for a JOIN and will look something like this:

SELECT users.id, users.nickname, messages.body, messages.timestamp 
   FROM messages JOIN users ON messages.recipient = users.id

Also, you should restructure your table so that you're storing the IDs as the right data type since that will make it much cleaner and will save the database the trouble of having to cast it later (or throw an error):

CREATE TABLE  `db.app`.`messages` (
  `id` INT( 32 ) NOT NULL AUTO_INCREMENT ,
  `sender` INT( 32 ) NOT NULL ,
  `recipient` INT( 32 ) NOT NULL ,
  `body` TEXT NOT NULL ,
  `timestamp` INT( 32 ) NOT NULL ,
  PRIMARY KEY (  `id` )
) ENGINE = MYISAM ;

Something like this should work (sender's id is assumed to be 1 and recipient's id is assumed to be 2):

SELECT users.id, users.nickname, messages.body, messages.timestamp
FROM messages
JOIN users ON messages.recipient = users.id
          AND messages.sender    = 1
          AND messages.recipient = 2

这正是你想要的:

SELECT users.id AS other_person_id, users.nickname AS other_person_nickname, messages.body AS last_message, messages.timestamp AS last_message_timestamp FROM messages LEFT JOIN users ON (messages.recipient = users.id) ORDER BY messages.id DESC LIMIT 1

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