[英]Selecting records from a table and then selecting a count of records from another table
I have two tables that looks like this; 我有两张看起来像这样的桌子;
Table: pictures
`picture_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`picture_title` varchar(255) NOT NULL,
`picture_description` text NOT NULL,
`picture_src` varchar(50) NOT NULL,
`picture_filetype` varchar(10) NOT NULL,
`picture_width` int(11) NOT NULL,
`picture_height` int(11) NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`upload_date` datetime NOT NULL,
-- -
Table: picture_votes
`vote_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`picture_id` int(10) unsigned NOT NULL,
`vote` tinyint(4) NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`timestamp` datetime NOT NULL,
And what I want to do is to select every field from pictures
table and then a count of all the records in picture_votes
where pictures.picture_id = picture_votes.picture_id
, like for example; 我想要做的是从
pictures
表中选择每个字段,然后在picture_votes
中所有记录的计数,其中pictures.picture_id = picture_votes.picture_id
,例如;
picture_id => 1
picture_title => 'Pic title'
picture_description => 'Pic description'
picture_src => 'b8b3f2c3a85f1a46fbf2ee132d81f783'
picture_filetype => 'jpg'
picture_width => 612
picture_height => 612
user_id => 1
upload_date => '2013-10-12 12:00:00'
vote_count => 3 // Amount of records in `picture_votes` that has `picture_id` = 1
I've come up with (where $limit
is the amount of pictures to select); 我想出了(其中
$limit
是要选择的图片数量);
SELECT pictures.*, count(picture_votes.vote) as vote_count
FROM pictures, picture_votes
WHERE pictures.picture_id = picture_votes.picture_id
ORDER BY upload_date DESC
LIMIT $limit
This selects only 1 picture and a count of all records in picture_votes
. 这仅选择1张图片和
picture_votes
中所有记录的计数。
You really want to use LEFT join, because that will return all the pictures, not just the ones with a vote. 你真的想要使用LEFT join,因为这将返回所有图片,而不仅仅是投票的图片。 You also should do sum(pv.vote) vs COUNT() incase your votes ever are more than 1 (hey, it can happen! Just think: Premium account == x2 votes ;-)
你也应该做总和(pv.vote)和COUNT(),如果你的选票超过1(嘿,它可能发生!只想:高级账户== x2票;-)
SELECT p.*, SUM(pv.vote) votes FROM pictures p
LEFT JOIN picture_votes pv
ON pv.picture_id=p.picture_id
GROUP BY pv.picture_id
If you ever wanted to sort by, say, top 10 vote count: 如果您想排序前10位投票数:
SELECT * FROM (
SELECT p.*, SUM(pv.vote) votes FROM pictures p
LEFT JOIN picture_votes pv
ON pv.picture_id=p.picture_id
GROUP BY pv.picture_id
) AS aggregate
ORDER BY votes DESC
LIMIT 10;
If picture_id
is indexed on your picture_votes
table, then the following may be even faster than a join: 如果
picture_id
在picture_votes
表上编入索引,那么以下内容甚至可能比连接更快:
SELECT *
, ( SELECT COUNT(*) FROM picture_votes WHERE picture_id = pictures.picture_id )
FROM pictures
This may skip the contents of the table entirely and allow you to simply count the records in the hash table, which should be faster. 这可能会完全跳过表的内容,并允许您简单地计算哈希表中的记录,这些记录应该更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.