MySQL子查询并加入3个表

时间:2014-07-17 04:24:10

标签: mysql sql left-join

我尝试从以下查询中加入另一个表:

SELECT * FROM users u,
  (SELECT submissions_comments.parent_id from submissions_comments where id = 96) x
WHERE u.id = x.parent_id\G

*************************** 1. row ***************************
            id: 17
         email: bobcobb@gmail.com
          hash: $2a$10$m9egfe.NtKC4QbR869el9.t.w0E7jN2Omk6AXQCbF/ERyfseJVx6S
          salt: $2a$10$m9egfe.NtKC4QbR869el9.
      username: test
          name:
          role: normal
         about:
       created: 2014-01-17 00:53:52
    last_login: 2014-01-17 08:53:52
    created_ip: 1270
 last_login_ip: 1270
   remember_me: 1
         photo: 
     confirmed: 0
  confirm_code: 814eaadfb411fb1a982c4b4b79b91cc37860c672
public_profile: 1
     parent_id: 17
1 row in set (0.00 sec)

基本上我想加入上面的user.id(在这种情况下是17)到另一个表。下面的查询为我提供了我想要添加到上述查询的内容:

SELECT email_reply_on_comment
  FROM email_settings
WHERE id = 17;

+------------------------+
| email_reply_on_comment |
+------------------------+
|                      0 |
+------------------------+

我正在尝试各种变体:

SELECT * FROM users u,
  (SELECT submissions_comments.parent_id from submissions_comments where id = 96) x,
  email_settings.reply_on_comment
WHERE u.id = x.parent_id
LEFT JOIN email_settings 
ON email_settings.user_id = x.parent_id;

但没有到达任何地方。

1 个答案:

答案 0 :(得分:0)

尝试以下加入:

SELECT u.*, es.email_reply_on_comment
FROM users u
INNER JOIN
  (SELECT submissions_comments.parent_id from submissions_comments where id = 96) x
ON u.id = x.parent_id
LEFT JOIN email_settings es
ON es.id = u.id;

<强>参考

MySQL LEFT JOIN on MySQLTutorial