一次从两个表中选择多个值

时间:2012-02-13 22:37:51

标签: php mysql email mysqli prepared-statement

代码

目前我的代码看起来像那样。

            $stmt = $this->db->prepare("SELECT m.id, m.from_id, m.to_id, m.subject, m.date, m.deleted, m.read, u.fname, u.mname, u.lname FROM msghistory AS m,users AS u WHERE m.from_id=u.id AND m.to_id=u.id AND GROUP BY m.id DESC");
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->affected_rows > 0) {
                $msg = array();
                $stmt->bind_result($msg['id'], $msg['from_name'], $msg['to_name'], $msg['subject'], $msg['message'], $msg['date'], $msg['deleted'], $msg['read']);

                while ($stmt->fetch()) {
                    <echoing results one by one>                    }
            }

我想做什么

我希望将u.fname+u.mname+u.lnamemsghistory.from_id=users.id)改为$msg['from_name'],再次u.fname+u.mname+u.lname这次msghistory.to_id=users.id )作为$ msg ['to_name']。

实施例

message | from_id | to-id
hi      | 1       | 5

如您所见,这意味着,用户1向用户5发送消息hi。

让我们在用户表fname中说,lname为用户id = 1 - John Doe和5 - George Smith 我想将此显示为输出结果

message | from_id | to-id
hi      | John Doe| George Smith

问题

我知道至少有3个查询是可能的。但试图找到最佳方式。那么,这可能只有一个查询吗?

更新

基于用户的2个有用答案,我将查询修改为此

            $stmt = $this->db->prepare("SELECT 
                message.id, message.from_id, message.to_id, message.subject, 
                message.date, message.deleted, message.read, 
                CONCAT_WS(' ',sender.fname, sender.mname, sender.lname) AS sender_name, 
                CONCAT_WS(' ',recipient.fname, recipient.mname, recipient.lname) AS recipient_name,  
                FROM msghistory AS message 
                LEFT JOIN users AS sender ON sender.id=message.from_id, 
                LEFT JOIN users AS recipient ON recipient.id=message.to_id 
                GROUP BY message.id DESC");

2 个答案:

答案 0 :(得分:1)

SELECT m.id, m.from_id, m.to_id, m.subject, m.date, 
m.deleted, m.read, u1.fname, u1.mname, u1.lname, 
u2.fname, u2.mname, u2.lname,       
FROM msghistory AS m,users AS u1, users As u2     
WHERE m.from_id=u1.id AND m.to_id=u2.id 
GROUP BY m.id DESC

我不确定你是否需要“分组”

答案 1 :(得分:1)

使用显式连接和清晰可读的别名使其既更强大,又更易于阅读。请尝试以下方法:

SELECT message.*, recipient.*, sender.*
FROM msghistory AS message
INNER JOIN users AS recipient ON recipient.id=m.to_id
INNER JOIN users AS sender ON sender.id=m.from_id

您可以将select * s替换为您想要提高效率的字段