If you want sequential rows from different tables, and for each table to return a different number of rows, then you can use UNION
. However, UNION
requires each SELECT
to return the same number of columns, so you will need to fill in the missing columns with a value (or NULL
), like this:
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 |
+----+------+------+
If you want to further process the UNION
result set, you can wrap it in another SELECT
, like this:
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 |
+------+------+
Is that what you are after?