简体   繁体   中英

After select sum php and mysql give me an error - subquery returns more than one row?

I have made some Vote script, where user vote up or down for some answers. It works fine when i have only one answer for question. If i give two or more answers for One question, the i got an error subquery returns more than one row .

$rezultati = mysqli_query($con,"SELECT SUM(down) as down 
FROM vote  WHERE answerId = 
(SELECT questionId FROM answers WHERE questionId = $id)");

while($row = mysqli_fetch_array($rezultati))
{

echo $row['down'];

}
mysqli_close($con);
?>

This is for UP button, and for Down is similar. (I know that there is simplier way to make all that, but i am new at php..) Here is table questions

CREATE TABLE IF NOT EXISTS `questions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question` text NOT NULL,
`user` varchar(255) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

And table Answers

CREATE TABLE IF NOT EXISTS `answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`answer` text COLLATE utf8_unicode_ci NOT NULL,
`questionId` int(11) NOT NULL,
`user` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
 )

And table Vote

CREATE TABLE IF NOT EXISTS `vote` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ip` varchar(50) NOT NULL,
`answerId` int(11) NOT NULL,
`up` int(11) NOT NULL,
`down` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

Where is the problem? How to fix that? Thank you!!

From your question I understand that you want to list all down votes for a certain question. Then, if you are updating the columns up and down to table answers , the query is simple.

"SELECT SUM(down) as down 
FROM answers WHERE questionId = $id)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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