从多个表中获取行

时间:2016-01-24 00:05:54

标签: mysql sql

如果我需要从productssubcontent表中获取image_id字段与$id匹配的行,我需要写什么样的查询?

图片表

mysql> show columns from images;
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(10)      | NO   | PRI | NULL    | auto_increment |
| file_name | varchar(255) | NO   |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

mysql> select * from images;
+----+-------------+
| id | file_name   |
+----+-------------+
|  1 | image_1.png |
|  2 | image_2.png |
|  3 | image_3.png |
|  4 | image_4.png |
+----+-------------+

产品表

mysql> show columns from products;
+----------+-----------------------+------+-----+---------+----------------+
| Field    | Type                  | Null | Key | Default | Extra          |
+----------+-----------------------+------+-----+---------+----------------+
| id       | mediumint(8) unsigned | NO   | PRI | NULL    | auto_increment |
| title    | text                  | NO   |     | NULL    |                |
| image_id | int(10) unsigned      | YES  |     | NULL    |                |
+----------+-----------------------+------+-----+---------+----------------+

mysql> select * from products;
+----+-----------------+----------+
| id | title           | image_id |
+----+-----------------+----------+
|  1 | Product Title 1 | 2        |
|  2 | Product Title 2 | 1        |
+----+-----------------+----------+

子内容表

mysql> show columns from subcontent;
+----------+------------------------+------+-----+---------+----------------+
| Field    | Type                   | Null | Key | Default | Extra          |
+----------+------------------------+------+-----+---------+----------------+
| id       | int(10) unsigned       | NO   | PRI | NULL    | auto_increment |
| title    | varchar(255)           | NO   | MUL | NULL    |                |
| image_id | mediumint(10) unsigned | NO   |     | NULL    |                |
+----------+------------------------+------+-----+---------+----------------+

mysql> select * from subcontent;
+----+--------------------+----------+
| id | title              | image_id |
+----+--------------------+----------+
|  1 | SubContent Title 1 | 2        |
|  2 | SubContent Title 2 | 3        |
+----+--------------------+----------+

结果我正在寻找$id=2

+---------------------+
| title               |
+---------------------+
| Product Title 1     |
| SubContent Title 1  |
+---------------------+

2 个答案:

答案 0 :(得分:1)

您可以使用UNION ALL语法:

SELECT title FROM products WHERE image_id = 2
UNION ALL
SELECT title FROM subcontent WHERE image_id = 2
  

UNION用于将多个SELECT语句的结果合并到一个结果集中。

答案 1 :(得分:1)

您需要使用UNION ALL

(SELECT title FROM products WHERE image_id = $id) UNION ALL (SELECT title FROM subcontent WHERE image_id = $id)