从MySQL中的单个表中查找给定结果的类似结果

时间:2013-01-30 10:17:41

标签: php mysql sql

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

  

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

我想在MySQL和PHP中显示所有与genderagecountry相同的人名。

最好的MySQL查询是什么?

4 个答案:

答案 0 :(得分: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 Fiddle Demo

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

| 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 |

AhmedMohammed(ID 2)和ali具有相同的GenderAgeCountry:{{1} }。

Male, 20, Egyptsaly相同。仅选择五个名称:

Sara

而其他人:

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

没有其他行具有相同的| 6 | Mohammed | Male | 60 | Egypt | | 7 | Khalid | Male | 20 | KSA | ,因此会被忽略。

答案 1 :(得分: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

看到它执行live

答案 2 :(得分: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将成为特定人的身份。

根据@fthiella评论

SELECT Name 
FROM table_name
WHERE (Gender, Age, Country) = (SELECT Gender, Age, Country FROM table_name WHERE id = $x)

答案 3 :(得分:0)

select `name` from `tablename` group by `gender`,`age `,`country`;