我在单个查询中尝试在只有其中一行符合特定条件时获取整个行集。在下面的例子中,我想对Mike Smith进行查询。如果我发现Mike Smith已经接受了测试(通过test_id),那么我想要包含该test_id的所有结果。因此,成功的查询将返回前7行。这可能不运行多个查询吗?下面是我的表的示例全部内容。
我无法使用
Select * where first_name = 'Mike';
因为这只会返回迈克的考试成绩;
当我得到迈克的结果时,我不知道如何选择所有考试成绩(多次考试)。
+------------+------------+-----------+-------+------+
| test_id | first_name | last_name | class | rank |
+------------+------------+-----------+-------+------+
| 1 | John | Doe | 2012 | 1 |
+------------+------------+-----------+-------+------+
| 1 | Jack | Smith | 2014 | 50 |
+------------+------------+-----------+-------+------+
| 1 | Mike | Smith | 2014 | 60 |
+------------+------------+-----------+-------+------+
| 2 | Mike | Smith | 2014 | 70 |
+------------+------------+-----------+-------+------+
| 2 | John | Smith | 2014 | 80 |
+------------+------------+-----------+-------+------+
| 3 | Jake | Smith | 2014 | 80 |
+------------+------------+-----------+-------+------+
| 3 | Mike | Smith | 2014 | 90 |
+------------+------------+-----------+-------+------+
| 4 | Jake | Smith | 2014 | 78 |
+------------+------------+-----------+-------+------+
答案 0 :(得分:1)
使用EXISTS
子句,例如
SELECT * FROM `test_table` a WHERE EXISTS (
SELECT 1 FROM `test_table` b
WHERE first_name = 'Mike'
AND last_name = 'Smith'
AND b.test_id = a.test_id
)
或者,你可以INNER JOIN
表格自己,例如
SELECT a.* FROM `test_table` a
INNER JOIN `test_table` b
ON a.test_id = b.test_id
WHERE b.first_name = 'Mike' AND b.last_name = 'Smith'
在这里演示 - http://sqlfiddle.com/#!2/c8646/1
答案 1 :(得分:0)
我认为这可能是你之后的事情:
SELECT *
FROM test_scores
WHERE test_id IN
(
SELECT test_id
FROM test_scores
WHERE first_name = 'Mike' AND last_name = 'Smith'
GROUP BY test_id
)
注意:我只是假设表名是' test_scores'