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
Puede agregar los siguientes filtros antes de GROUP BY
:
- Año:
WHERE YEAR(a.ad_birthday) = '2012'
- País:
WHERE b.country = 'Albania'
Véalo en acción .
Luego, después de convertir su mysql_
funciones a mysqli_
o PDO
(porque está siendo obsoleto
), simplemente puede mostrar el resultado por género:
| GENDER | COUNT | ------------------ | Female | 2 | | Male | 1 |
Actualización 1
Para implementar este código, puede probar algo como esto (no probado):
$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);
Actualización 2
Como no puede usar mysqli
por alguna razón, el siguiente código debería funcionar. Tenga en cuenta que se supone que ese país no está vacío.
$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";
}