SELECT c.gender, COUNT(*) AS 'count'
FROM ads a
INNER JOIN
(SELECT fieldvalue, fieldtitle AS country FROM field_values) b
ON b.fieldvalue = a.ad_country
INNER JOIN
(SELECT fieldvalue, fieldtitle AS gender FROM field_values) c
ON c.fieldvalue = a.ad_gender
GROUP BY c.gender
Du kan lägga till följande filter före GROUP BY
:
- År:
WHERE YEAR(a.ad_birthday) = '2012'
- Land:
WHERE b.country = 'Albania'
Se den in action .
Sedan efter att du konverterat din mysql_
funktioner till mysqli_
eller PDO
(eftersom den håller på att utfasas
), kan du helt enkelt visa resultatet efter kön:
| GENDER | COUNT | ------------------ | Female | 2 | | Male | 1 |
Uppdatering 1
För att implementera den här koden kan du prova något i stil med detta (ej testat):
$link = mysqli_connect("localhost", "user_name", "password", "stock");
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$stmt = mysqli_prepare($link, "SELECT c.gender, COUNT(*) AS 'count' FROM ads a
INNER JOIN (SELECT fieldvalue, fieldtitle AS country FROM field_values) b ON b.fieldvalue = a.ad_country
INNER JOIN (SELECT fieldvalue, fieldtitle AS gender FROM field_values) c ON c.fieldvalue = a.ad_gender
WHERE b.country = ? AND (YEAR(a.ad_birthday) = ? OR YEAR(a.ad_birthday) <> NULL) GROUP BY c.gender");
mysqli_bind_param($stmt, 'ss', $country, $year) or die(mysqli_error($dbh));
$result = mysqli_stmt_execute($stmt) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result)) {
echo "There are " . $row[count] . ' ' . $row[gender] . "<br />\n";
}
mysqli_close($link);
Uppdatering 2
Eftersom du inte kan använda mysqli
av någon anledning borde koden nedan fungera. Observera att det förutsätter att landet inte är tomt.
$query = "SELECT c.gender, COUNT(*) AS 'count' FROM ads a
INNER JOIN (SELECT fieldvalue, fieldtitle AS country FROM field_values) b ON b.fieldvalue = a.ad_country
INNER JOIN (SELECT fieldvalue, fieldtitle AS gender FROM field_values) c ON c.fieldvalue = a.ad_gender
WHERE b.country = " . mysql_real_escape_string($country);
if(isset($year)) $query .= " AND YEAR(a.ad_birthday) = " . mysql_real_escape_string($year);
$query .= ' GROUP BY c.gender';
$sql2 = mysql_query($query);
while($row = mysql_fetch_assoc($sql2)) {
echo "There are " . $row[count] . ' ' . $row[gender] . "<br />\n";
}