两次左连接

时间:2017-06-20 23:27:09

标签: mysql

我有两张桌子

SELECT *
FROM messages
LEFT JOIN users ON user_id = msg_to
WHERE msg_id = $msg_id

$user_name = $row['user_name'];
$message_text = $row['message_text'];

我使用简单的JOIN来检索变量

$message_from = $row['user_name'];
$message_to = $row['user_name'];

如何从同一个表中获取2个变量?

MSG ID     FROM     TO     TEXT
1          Paul     Mark   Blah

我期待这样的结果:

$ last_entry_line=$(grep -n '^FIXES ' test.txt | tail -1 | cut -d: -f1 )
$ cat test.txt | sed -n "${last_entry_line},/Committ/p" | sed '/^FIXES/s/\([:;]\)\s*/\1;\n/g'

1 个答案:

答案 0 :(得分:1)

SELECT message_text, 
   to_users.user_name as to_user, 
   from_users.user_name as from_user
FROM messages
LEFT JOIN users as to_users ON user_id = message_to_id
LEFT JOIN users as from_users ON user_id = message_from_id
WHERE message_id = $msg_id;

$message_from = $row['from_user'];
$message_to = $row['to_user'];
$message_text = $row['message_text'];

切向,我建议您养成使用预处理语句的习惯,如果您使用的是PHP,而不是像$msg_id那样使用字符串中的变量。这有助于保护您免受SQL注入攻击。