连接2个表为每个相关数据返回单行

时间:2015-04-15 15:44:54

标签: mysql

我正在尝试使用不同的照片网址加入两张桌子,但我无法这样做。我不知道是否可能。

我的表格与下面的示例类似,我想加入它们。

+-------------------+     +----------------------------+
|       table1      |     |           table2           |
+----+------+-------+     +----+-----------+-----------+
| id | name | place |     | id | photo_url | table1_id |
+----+------+-------+     +----+-----------+-----------+
|  1 | abc  | xyz   |     |  1 | link1     |         1 |
|  2 | def  | jiu   |     |  2 | link2     |         1 |
|  3 | efw  | jlo   |     |  3 | link3     |         3 |
+----+------+-------+     |  4 | link4     |         2 |
                          +----+-----------+-----------+
+-------------------------------+
|          joined_tbl           |
+----+------+-------+-----------+
| id | name | place | photo_url |
+----+------+-------+-----------+
|  1 | abc  | xyz   | link1     |
|  2 | def  | jiu   | link3     |
|  3 | efw  | jlo   | link4     |
+----+------+-------+-----------+

我是MySQL的新手并且还在学习它。我被困在这里,我很感激任何解决方案。

3 个答案:

答案 0 :(得分:1)

您可以使用JOIN

SELECT t1.*,
  t2.photo_url
FROM table1 t1
JOIN table2 t2
  ON (t1.id = t2.table1_id)
JOIN (
  SELECT min(id) AS id,
    table1_id
  FROM table2
  GROUP BY table1_id
) t3 ON (t2.id = t3.id
   AND t2.table1_id = t3.table1_id)

JOIN的自table2版仅按table1_id选择照片。


➜ SQLFiddle Demo

答案 1 :(得分:0)

您尝试过类似的事情吗?

SELECT table1.id,
  table1.name,
  table1.place,
  table2.photo_url
FROM table1
LEFT JOIN table2
  ON table1.id = table2.table1_id;

我基本上根据id条件从您的表格中选择了所需的字段。

您可以在此处查看MySQL教程:http://www.w3schools.com/sql/default.asp

答案 2 :(得分:0)

取决于您如何定义所需的photo_url值。

假设只有MIN一个: -

SELECT table1.id,
  table1.name,
  table1.place,
  MIN(table2.photourl)
FROM table1
LEFT OUTER JOIN table2
  ON table1.id = table2.table1_id
GROUP BY table1.id,
  table1.name,
  table1.place

如果你不在乎哪一个(虽然这在MySQL中有用,但它是狡猾的SQL): -

SELECT table1.id,
  table1.name,
  table1.place,
  table2.photo_url
FROM table1
LEFT OUTER JOIN table2
  ON table1.id = table2.table1_id
GROUP BY table1.id,
  table1.name,
  table1.place

如果您想要更复杂的东西,那么您可能需要使用子查询来为每个photo_url获取所选table1_id,然后JOIN该子查询到table1