[英]How to query a second table for each result from a first table?
I'm not really sure how to do this - I only posses a limited knowledge of joins in MySQL, and from what I read I don't think they'd be of much use here. 我不太确定该怎么做-我对MySQL中的联接知识只有有限的了解,从我读到的内容来看,我认为它们在这里没有多大用处。
Essentially, I have 2 tables: 本质上,我有2个表:
images votes
--------------------------- ------------------------------
image_id | name | square_id vote_id | image_id | vote_type
--------------------------- ------------------------------
1 img1 14 1 4 1
2 img2 3 2 17 0
3 img7 72 3 2 1
... ...
n imgn 1478 n n 1
What I'd like to do is get the details of each image and the number of votes cast (plus the vote_type
) on each image where a certain condition is true (such as where each image has a certain square_id
). 我想做的是获取每个图像的详细信息, 以及在vote_type
特定条件(例如,每个图像都有特定square_id
)的情况下在每个图像上投的票数(加上 square_id
)。 Executing the first part of this query is easy: 执行此查询的第一部分很容易:
SELECT `image_id`, `name` FROM `images` WHERE `square_id` = :boundParameter;
But, I'm unsure of how to get each vote_id
and vote_type
for each image that meets the original WHERE condition in my query. 但是,我不确定如何为查询中满足原始WHERE条件的每个图像获取每个vote_id
和vote_type
。
How would I accomplish this? 我将如何完成?
This is actually a really simple join between tables. 这实际上是表之间非常简单的联接。 You really, really should read this Q&A that I put together about SQL and queries and joins between two tables. 您确实应该阅读我整理的有关SQL和查询以及两个表之间的联接的问答 。
In the meantime, this will probably give you what you want: 同时,这可能会给您您想要的东西:
select
img.image_id,
img.name,
img.square_id,
count(vot.vote_id) as numberVotes,
vot.vote_type
from
images img
join votes vot
on img.image_id=vot.image_id
group by
img.image_id,
img.name,
img.square_id,
vot.vote_type
So, with that, first off, you don't want multiple queries, you want to use one query here. 因此,首先,您不需要多个查询,而是要在此处使用一个查询。 Running multiple connections/queries to a database is a MUCH higher overhead than running one query that fetches all the data you want. 与运行一个查询以获取所需的所有数据的查询相比,对数据库运行多个连接/查询的开销要高得多。
Try it like this: 像这样尝试:
SELECT images.image_id, images.name , votes.vote_id , votes.vote_type
FROM images
LEFT JOIN votes ON images.image_id = votes.image_id
WHERE `square_id` = :boundParameter;
SELECT images.image_id,
images.name,
votes.vote_id,
votes.vote_type
FROM images
LEFT JOIN votes ON images.image_id = votes.image_id
WHERE images.square_id = :boundParameter;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.