mysql查询失败

时间:2012-02-27 07:57:39

标签: php mysql

我对mysql查询有一个小问题

我有2张表A和B

table A {id, name, gender}
table B{id, name, salary}

我想查询获取name, gender, salary,但我的查询似乎只获得namegender

查询是:

select * from tableA inner join tableB on tableB.id=tableA.id ;

3 个答案:

答案 0 :(得分:1)

SELECT a.name, a.gender, b.salary
FROM tableA AS a
LEFT JOIN tableb AS b ON(a.id = b.id)
WHERE 1;

答案 1 :(得分:0)

尝试

select Ta.name, Ta.gender, Tb.salary from tableA as Ta join tableB as Tb on Ta.id = Tb.id;

或者你可以尝试

select Ta.name, Ta.gender, Tb.salary from tableA Ta, tableB Tb where Ta.id = Tb.id;

两个查询都可以正常工作。

答案 2 :(得分:0)

我无法重现你的问题。

<?php
define('QUERY', 'select * from tableA inner join tableB on tableB.id=tableA.id');

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);
echo PHP_VERSION, "\n";
echo 'client: ', $pdo->getAttribute(PDO::ATTR_CLIENT_VERSION), "\n";
echo 'server: ', $pdo->getAttribute(PDO::ATTR_SERVER_VERSION), "\n";

foreach( $pdo->query(QUERY, PDO::FETCH_ASSOC) as $row ) {
    print_r($row);
}

function setup(PDO $pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE tableA (
            id int,
            name varchar(16),
            gender int,
            key(id)
        )
    ');
    $pdo->exec('
        CREATE TEMPORARY TABLE tableB (
            id int,
            name varchar(16),
            salary int,
            key(id)
        )
    ');
    $pdo->exec("INSERT INTO tableA (id,name,gender) VALUES (1, 'nA', 1), (2, 'nb', 1), (3, 'nc', 1), (4, 'nd', 1)");
    $pdo->exec("INSERT INTO tableB (id,name,salary) VALUES (1, 'nA', 1), (2, 'nb', 4), (3, 'nc', 9), (4, 'nd', 16)");
}

打印

5.3.8
client: mysqlnd 5.0.8-dev - 20102224 - $Revision: 310735 $
server: 5.5.16
Array
(
    [id] => 1
    [name] => nA
    [gender] => 1
    [salary] => 1
)
Array
(
    [id] => 2
    [name] => nb
    [gender] => 1
    [salary] => 4
)
Array
(
    [id] => 3
    [name] => nc
    [gender] => 1
    [salary] => 9
)
Array
(
    [id] => 4
    [name] => nd
    [gender] => 1
    [salary] => 16
)

(如预期的那样)。