有一些SQL子查询问题,从一个查询中获取查询结果并使用它来过滤下一个结果

时间:2017-05-04 03:26:01

标签: mysql

从一个查询中获取查询结果并使用它来过滤下一个结果时出现一些SQL子查询问题

表1我从查询一中得到了结果,但我想使用fav的结果从我的团队表中过滤,我有很多团队,它会显示结果

mysql> SELECT fav FROM login WHERE username ='djk';
+-------------+
| fav         |
+-------------+
| Real Madrid |
+-------------+
1 row in set (0.00 sec)

我试过这个

(SELECT fav FROM login WHERE username ='djk') as team_name  from team;

和许多其他人没有工作

这是我的团队表,所以我想使用一个查询的结果从team_name过滤,只显示请求的团队

mysql> describe team ;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| team_id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| team_name   | varchar(355) | NO   |     | NULL    |                |
| country     | varchar(255) | YES  |     | NULL    |                |
| stadium     | varchar(255) | YES  |     | NULL    |                |
| city        | varchar(255) | YES  |     | NULL    |                |
| coach       | varchar(255) | YES  |     | NULL    |                |
| league_name | varchar(255) | NO   |     | NULL    |                |
| league_id   | int(11)      | NO   | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

如果有人可以指导我朝着正确的方向前进,我会选择它。

3 个答案:

答案 0 :(得分:0)

WHERE子句中的一个简单子查询应该可以正常工作:

SELECT * FROM team WHERE team_name = (SELECT fav FROM login WHERE username = 'djk'

答案 1 :(得分:0)

您的用例是inner join

select *
from team t
join login l on t.team_name = l.fav
where l.username ='djk';

答案 2 :(得分:0)

Thanks for the help  i was able to do it with where

<?php
ob_start();
echo $_SESSION['username'] ;
$getname = ob_get_contents();
ob_end_clean();

                            $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn) {
                                echo "here";
}
                    $sql3 = "SELECT * from team where team_name =(select fav from login where username='${getname}')";