0

我有一个包含这些列的表:

id - 姓名 - 性别 - 年龄 - 国家

我想显示所有具有相同名称的人genderage以及countryMySQL 和 PHP 中的某个人。

什么是最好的 MySQL 查询?

4

4 回答 4

2

尝试这个:

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只出现一次,那么这些名称将被忽略。

SQL 小提琴演示

例如,让我们有以下示例数据:

| 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,AgeCountry: Male, 20, Egypt

saly和相同Sara。将仅选择五个名称:

|     NAME |
------------
|    Ahmed |
| Mohammed |
|      ali |
|     Saly |
|     Sara |

而其他人:

|  6 | Mohammed |   Male |  60 |   Egypt |
|  7 |   Khalid |   Male |  20 |     KSA |

没有其他行具有相同的Gender, Age, Country,因此它们被忽略。

于 2013-01-30T10:30:45.613 回答
2
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

看它现场表演

于 2013-01-30T10:30:48.127 回答
1
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)
于 2013-01-30T10:24:57.827 回答
0
select `name` from `tablename` group by `gender`,`age `,`country`;
于 2013-01-30T10:26:23.940 回答