从2个表中选择信息会返回错误

时间:2017-07-25 09:00:53

标签: php mysql

我这样做

<?php
require_once('inc/config.php');
$con = mysqli_connect($host, $user, $pass, $db) or die ('Cannot Connect : '.mysqli_error());
$sql = "select username from education_info,profile_info where username ='j_spaxx22'";
$result = mysqli_query($con,$sql)  or die("Error: ".mysqli_error($con));
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) )
{
    echo $row['fullname'] ."". $row['email'] ."". $row['city'] ."". $row['state'] ."". $row['lga'] ."". $row['inst_name'] ."". $row['study_course'];
}
?>

我得到了这个错误

  

错误:列&#39;用户名&#39;在字段列表中是不明确的

我错了什么?

编辑:

当我像这样进行查询时

$sql = "select * from education_info,profile_info";

我正确地获得了所有表格

但是当我做这样的事情时

$sql = "select username from education_info,profile_info where username ='j_spaxx22'";

我得到一个错误,我似乎变得错了什么?

5 个答案:

答案 0 :(得分:0)

您的表username

中有2列具有相同名称education_info,profile_info的列

如果您不需要JOIN表格,只需从您想要的表格中选择

即可
select username 
from education_info
where username ='j_spaxx22'

OR

select username 
from profile_info
where username ='j_spaxx22'

如果您需要JOIN表格

SELECT profile.username 
FROM profile_info      profile
JOIN education_info    education ON profile.columntojoin=education.columntojoin
WHERE profile.username ='j_spaxx22'

请注意,在每个表之后,为每个表提供ALIAS,您可以从中表示要从哪个表中显示数据。例如profile.username。当2个表连接具有相同的列名时,它们也需要使用表名别名来标识,否则会出现Column in field list is ambiguous错误。

当你使用*而没有WHERE时,MySQL将返回完整的数据集,因为它可以只显示数据,当使用像WHERE这样的过滤器时,MySQL必须知道哪一列确切地存在于多个表中。

答案 1 :(得分:0)

使用此查询并获取没有错误的输出,只需使用tablename;

Integer

答案 2 :(得分:0)

您可以使用此查询

SELECT用户名 来自education_info WHERE username ='j_spaxx22' 联盟 SELECT用户名 来自profile_info WHERE username ='j_spaxx22' ;

答案 3 :(得分:0)

试试这个。

        $sql="select 
        education_info.username as un, education_info.col2 as c2, 
        education_info.col3 as c3, 
        profile_info.username as un2, profile_info.col2 as c4 
        from education_info LEFT JOIN profile_info ON 
        education_info.username=profile_info.username 
        AND profile_info.username ='whatever';";

答案 4 :(得分:-1)

您应该首选具有完整表名的字段,例如:

如果username字段来自education_info表,则sql语句应为:

select education_info.username from education_info,profile_info where education_info.username ='j_spaxx22';