外连接两个select语句的输出--mysql

时间:2013-08-11 17:59:04

标签: mysql select join outer-join

我正在尝试连接两个select语句的输出,因为每个select语句将返回0或1输出,如果一个返回0输出,INNER JOIN将不返回任何内容。 我想知道OUTER如何加入。 我已经看到INNER JOIN的解决方案,并且已经有一个工作但是,当我将其更改为OUTER JOIN时,我收到此错误:

错误代码:1064。您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在'OUTER JOIN(SELECT value FROM server_setting WHERE server_id = 1 AND server_sett'第3行附近使用正确的语法

这是查询:

SELECT * FROM
(SELECT `value` AS url FROM server_setting WHERE server_id=1 AND server_setting_type_id=(SELECT min(id) FROM server_setting_type WHERE type='url')) AS t1
FULL OUTER JOIN
(SELECT `value` AS port FROM server_setting WHERE server_id=1 AND server_setting_type_id=(SELECT min(id) FROM server_setting_type WHERE type='port')) AS t2
;

示例输入:

server_setting表:

|---------|----------------------|-----|
|server_id|server_setting_type_id|value|
|---------|----------------------|-----|
|1        |1                     |http |
|1        |2                     |22   |
|---------|----------------------|-----|

server_setting_type表:

|--|----|
|id|type|
|--|----|
|1 |url |
|2 |port|
|--|----|

结果:

|----|----|
|url |port|
|----|----|
|http|22  |
|----|----|

感谢

1 个答案:

答案 0 :(得分:2)

您的查询是:

SELECT *
FROM (SELECT `value` AS url
      FROM server_setting
      WHERE server_id=1 AND
            server_setting_type_id=(SELECT min(id)
                                    FROM server_setting_type
                                    WHERE type='url')
     ) AS t1 FULL OUTER JOIN
     (SELECT `value` AS port
      FROM server_setting
      WHERE server_id=1 AND
            server_setting_type_id=(SELECT min(id)
                                    FROM server_setting_type
                                    WHERE type='port')
    ) AS t2;

有几件事。首先,MySQL不支持full outer join(这是你得到错误的地方。其次,你没有on子句。第三,server_setting_type表似乎很奇怪对于“port”和“url”会有多行。我的第一个建议是做cross join而不是full outer join。这可能会做你想要的。

但是,出于某种原因,我认为以下内容可能更接近您真正想要的内容:

      SELECT sst_url.value as url, sst_port.`value` AS port
      FROM server_setting ss left outer join
           server_setting_type sst_url
           on ss.server_setting_type_id = sst_port.id and
              sst.type = 'url' left outer join
           server_setting_type sst_port
           on ss.server_setting_type_id = sst_port.id and
              sst.type = 'port'
      where ss.server_id = 1;

此版本 假设id中只有一个server_setting_type表示“url”,另一个表示“port”。这对我来说似乎很合理。