[英]Join 2 mysql queries, where the second query depends on the output of the first
I use my first query to get the id and name of the user like this:我使用我的第一个查询来获取用户的 ID 和名称,如下所示:
select id,name from temp_card where sex='$sex' and city='$city' order by name ASC
Then I have a second query that uses the results from the first, and gets more data from another table:然后我有第二个查询,它使用第一个查询的结果,并从另一个表中获取更多数据:
select images from temp_card_images where temp_card_id=". $row['id'] ." order by id ASC limit 1
How can I combine these two queries so that I can print out the 3 fields (id, name and images) in a single while loop?我如何组合这两个查询,以便我可以在一个 while 循环中打印出 3 个字段(id、name 和 images)?
Thank you!谢谢!
You needs to perform a JOIN query您需要执行 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
You need to learn about JOINs.您需要了解 JOIN。 This can be achieved like this
这可以这样实现
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.