简体   繁体   English

加入 2 个 mysql 查询,其中第二个查询依赖于第一个的 output

[英]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

Although unrelated, I would highly recommend looking into using PDO as your database access layer.尽管不相关,但我强烈建议您考虑使用PDO作为您的数据库访问层。 It works with most database types like MySQL, SQLite, etc.. and it will help against SQL injection to your database.它适用于大多数数据库类型,如 MySQL、SQLite 等。它有助于防止 SQL 注入您的数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM