MYSQL - 如何在单个查询中选择不相交的列?

时间:2010-07-01 06:42:31

标签: mysql mysqli

我有4个表,每个表有不同的列,但它们都有一个共同的列。这是一个整数标识符列。所以我将得到一些整数x,并且我希望所有4个表中具有这一个id列的所有行都等于x。

我尝试过类似的东西:

SELECT table1.col1, table2.col2 FROM table1 LEFT JOIN table2 ON table1.id=x OR coastlinessports.id=x

然后我回到了同一行中两个表都有列的行。

因此,一个结果块将具有:

table1.col1, table2.col2

但我真的想要:

table1.col1
tale2.col2

有没有办法可以连续执行4个选择查询?

4 个答案:

答案 0 :(得分:2)

如果您想要来自不同表的连续行,并且每个表返回不同数量的行,那么您可以使用UNION。但是,UNION要求每个SELECT返回相同数量的列,因此您需要使用值(或NULL)填充缺少的列,如下所示:

DROP TABLE IF EXISTS `table1`;
DROP TABLE IF EXISTS `table2`;

CREATE TABLE `table1` (
  `id` int(11) NOT NULL auto_increment,
  `col1` VARCHAR(255),
  `col2` VARCHAR(255),
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

CREATE TABLE `table2` (
  `id` int(11) NOT NULL auto_increment,
  `col1` VARCHAR(255),
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

INSERT INTO `table1` VALUES
    (1, '1,1', '1,2'),
    (2, '2,1', '2,2');

INSERT INTO `table2` VALUES
    (1, '1,1'),
    (2, '2,1');

SELECT `id`, `col1`, `col2` FROM `table1` WHERE `id` = 1
UNION
SELECT `id`, `col1`, NULL AS `col2` FROM `table2` WHERE `id` = 1;

+----+------+------+
| id | col1 | col2 |
+----+------+------+
|  1 | 1,1  | 1,2  |
|  1 | 1,1  | NULL |
+----+------+------+

如果您想进一步处理UNION结果集,可以将其包装在另一个SELECT中,如下所示:

SELECT `col1`, `col2` FROM (
    SELECT `id`, `col1`, `col2` FROM `table1` WHERE `id` = 1
    UNION
    SELECT `id`, `col1`, NULL AS `col2` FROM `table2` WHERE `id` = 1
) AS `t1`
ORDER BY col2;

+------+------+
| col1 | col2 |
+------+------+
| 1,1  | NULL |
| 1,1  | 1,2  |
+------+------+

这就是你追求的目标吗?

答案 1 :(得分:0)

这可能不会回答你的问题,但是JOIN会有一些奇怪的东西。

通常“ON”条件是指两个表都被连接,类似于:

... FROM table1 LEFT JOIN table2 ON table1.id = table2.id ...

我想有些情况下你不会这样做,但我想不出任何。

答案 2 :(得分:0)

如果表调用相同,则可以使用USING 对于给定值的部分,使用WHERE

select * from table1 join table2 using(commonColumn) join table3 using(commonColumn) join table4 using(commonColumn) where commonColumn="desiredValue"

更新:第二次阅读您的问题 你想要这个吗?

table1的所有行,其中commonColumn =“desiredValue”
其次是 table2的所有行,其中commonColumn =“desiredValue”
其次是 table3的所有行,其中commonColumn =“desiredValue”
其次是 table4的所有行,其中commonColumn =“desiredValue”

如果是这样,你需要使用UNION(你需要做4次选择) 如果列数不同,则需要填充空白别名

SELECT col1, col2, col3, col4 from table1 where commonColumn="desiredValue"  
UNION
SELECT col1, col2, 0 as col3, 0 as col4 from table2 where commonColumn="desiredValue"  
...

答案 3 :(得分:0)

相关问题