【问题标题】:select from table using an specific row values使用特定行值从表中选择
【发布时间】:2025-12-23 14:30:11
【问题描述】:

基本上我想选择基于特定行值的行。 例如,我有一个如下所示的表格:

id   name    sport      score    gender
1    tom     tennis      5       male
2    mia     football    9       male  
3    maria   tennis      7       male
4    liam    swimming    8       female

我试过这个 php 脚本:

$query = "select sport , score , gender from sprot_table where id = 1" ;
$res = $con->query($query) ;
$data = $res->fetch_assoc() ;
$sport = $data['sport']  ; $sport = $data['score']  ; $sport = $data['gender']  ; 
$query = "select id , name from sport_table where sport = $sport and gender = $gender and score > $score" ;
$con->query($query) ;

并且还尝试了这个 sql 代码:

select 
     id , name 
from sport_table where 
sport = ( select sport form sport_table where id = 1 ) and 
gender = ( select gender form sport_table where id = 1 ) and 
score > ( select score form sport_table where id = 1 ) 

我认为它们都没有经过优化。我相信应该有更好的方法来做到这一点 也许这个例子很简单,但你考虑更复杂的情况

【问题讨论】:

  • 样本数据、期望的结果以及对您的意图的清晰解释将真正有帮助。
  • abootorabi,你试试查询吗?
  • 是的,我试试你推荐的查询,它成功了,谢谢

标签: php sql database


【解决方案1】:

你可以试试这个查询:

select a.* from
(select * from sport_table) a,
(select * from sport_table where id=1)b
where a.sport=b.sport and a.gender=b.gender and a.score>b.score

【讨论】: