假设我有两张 table 。一个包含项目列表,一个包含项目的图片。
像这样:
项目
+----+---------+
| id | name |
+----+---------+
| 1 | oranges |
| 2 | apples |
+----+---------+
图片
+----+---------+
| id | item_id |
+----+---------+
| 1 | 1 |
| 2 | 2 |
| 3 | 2 |
+----+---------+
我的问题是这样的:是否可以在单个查询中从 Items
中选择项目 2
并连接 Pictures
中的所有行表的 item_id
引用了相同的 id?
我确信我已经尝试了几乎所有我能想到的方法,但什么也没有想到。如果答案很简单,我深表歉意,但我现在只是想不起来。
编辑
@Andomar,这有效,但它并没有完全给我我想要的结果。我想我应该更清楚地问是否有可能得到类似于这样的结果(它是一个 php 数组,但组织就是我想要的):
$results = array(
[0] => array(
'id' => 1,
'name' => 'oranges',
'images' => array(
[0] => ...,
),
),
[1] => array(
'id' => 2,
'name' => 'apples',
'images' => array(
[0] => ...,
[1] => ...,
),
),
);
最佳答案
加入应该可以解决问题:
select *
from Items i
left join Pictures p on p.item_id = i.id
where i.id = 2
关于MySQL,在单个查询中将一项与多项结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2862356/