我有一个包含这些列的表:
id - 姓名 - 性别 - 年龄 - 国家
我想显示所有具有相同名称的人gender
,age
以及country
MySQL 和 PHP 中的某个人。
什么是最好的 MySQL 查询?
尝试这个:
SELECT p1.Name
FROM peoplenames p1
INNER JOIN
(
SELECT Gender, Age, Country
FROM peoplenames p1
GROUP BY Gender, Age, Country
HAVING COUNT(*) > 1
) p2 ON p1.Gender = p2.Gender
AND p1.Age = p2.Age
AND p1.Country = p2.Country;
这将忽略那些没有Gender, Age, Country
.
这将为您提供具有相同的名称Gender, Age, Country
。但如果这种组合Gender, Age, Country
只出现一次,那么这些名称将被忽略。
例如,让我们有以下示例数据:
| ID | NAME | GENDER | AGE | COUNTRY |
------------------------------------------
| 1 | Ahmed | Male | 20 | Egypt |
| 2 | Mohammed | Male | 20 | Egypt |
| 3 | ali | Male | 20 | Egypt |
| 4 | Saly | Female | 25 | Jordan |
| 5 | Sara | Female | 25 | Jordan |
| 6 | Mohammed | Male | 60 | Egypt |
| 7 | Khalid | Male | 20 | KSA |
Ahmed
, Mohammed
(id 为 2) 并且ali
具有相同的Gender
,Age
和Country
: Male, 20, Egypt
。
与saly
和相同Sara
。将仅选择五个名称:
| NAME |
------------
| Ahmed |
| Mohammed |
| ali |
| Saly |
| Sara |
而其他人:
| 6 | Mohammed | Male | 60 | Egypt |
| 7 | Khalid | Male | 20 | KSA |
没有其他行具有相同的Gender, Age, Country
,因此它们被忽略。
SELECT
yt.*
FROM yourTable AS yt
JOIN
(SELECT * FROM yourTable yt2 WHERE id = $id) yt3
ON yt.Gender = yt3.Gender AND yt.Age = yt3.Age AND yt.Country = yt3.Country
看它现场表演
SELECT Name
FROM table_name
WHERE Gender = (SELECT Gender FROM table_name WHERE id = $x) AND
Age = (SELECT Age FROM table_name WHERE id = $x) AND
Country = (SELECT Country FROM table_name WHERE id = $x);
$x
将是特定人的 id。
根据@fthiella 评论
SELECT Name
FROM table_name
WHERE (Gender, Age, Country) = (SELECT Gender, Age, Country FROM table_name WHERE id = $x)
select `name` from `tablename` group by `gender`,`age `,`country`;