我使用第一个查询来获得用户的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)?
谢谢!
您需要执行一个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
您需要了解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
虽然不相关,但我强烈建议您考虑使用PDO作为数据库访问层。它适用于大多数数据库类型,如MySQL、SQLite等。它将有助于防止SQL注入数据库。