1

我使用我的第一个查询来获取用户的 ID 和名称,如下所示:

select id,name from temp_card where sex='$sex' and city='$city' order by name ASC

然后我有第二个查询,它使用第一个查询的结果,并从另一个表中获取更多数据:

select images from temp_card_images where temp_card_id=". $row['id'] ." order by id ASC limit 1

如何结合这两个查询,以便在单个 while 循环中打印出 3 个字段(id、name 和 images)?

谢谢!

4

3 回答 3

3

您需要执行 JOIN 查询

select tc.id, tc.name, tci.images from temp_card tc
left join temp_card_images  tci
on tc.id = tci.temp_card_id
where tc.sex='$sex' and tc.city='$city' order by tc.name ASC
于 2012-04-06T09:54:51.000 回答
2

您需要了解 JOIN。可以这样实现

SELECT tc.id,tc.name,tci.images
FROM temp_card tc
    INNER JOIN temp_card_images tci ON tc.id=tci.temp_card_id
WHERE sex='$sex' 
  AND city='$city' 
GROUP BY tc.id
ORDER BY name ASC
于 2012-04-06T09:55:13.373 回答
0

尽管不相关,但我强烈建议您考虑使用PDO作为您的数据库访问层。它适用于大多数数据库类型,如 MySQL、SQLite 等。它有助于防止 SQL 注入到您的数据库中。

编辑

删除了答案,因为给定的连接是更好的答案。

于 2012-04-06T09:58:53.783 回答