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
Vous pouvez ajouter les filtres suivants avant GROUP BY
:
- Année :
WHERE YEAR(a.ad_birthday) = '2012'
- Pays :
WHERE b.country = 'Albania'
Voir en action .
Ensuite, après avoir converti votre mysql_
fonctions à mysqli_
ou PDO
(parce qu'il est obsolète
), vous pouvez simplement afficher le résultat par sexe :
| GENDER | COUNT | ------------------ | Female | 2 | | Male | 1 |
Mise à jour 1
Pour implémenter ce code, vous pouvez essayer quelque chose comme ceci (non testé) :
$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);
Mise à jour 2
Puisque vous ne pouvez pas utiliser mysqli
pour une raison quelconque, le code ci-dessous devrait fonctionner. Veuillez noter qu'il suppose que le pays n'est pas vide.
$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";
}