如何将mysql表中的两个值放入一个变量中?

时间:2018-02-12 12:36:55

标签: mysql select pdo

这是我的查询的样子:

$pdo = $db->prepare('SELECT *,
s.name as name,
s.firstname as firstname,
FROM projects pj
LEFT JOIN school s ON pj.teacher=s.id 
WHERE project_id = :project_id ');  
$pdo->execute(array('project_id' => $project_id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    echo $row["firstname"].' '.$row["name"];
}

我想知道是否有办法将两个值放入一个变量中。我想象这样的事情:

$pdo = $db->prepare('SELECT *,
s.firstname.''.name as teacher,
FROM projects pj
LEFT JOIN school s ON pj.teacher=s.id 
WHERE project_id = :project_id ');  
$pdo->execute(array('project_id' => $project_id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    echo $row["teacher"];
}

2 个答案:

答案 0 :(得分:1)

如果你正在使用mysql,你可以concat连接:

SELECT *,
CONCAT(s.firstname, s.name) as teacher,
FROM projects pj
LEFT JOIN school s ON pj.teacher=s.id 
WHERE project_id = :project_id 

http://www.mysqltutorial.org/sql-concat-in-mysql.aspx

答案 1 :(得分:1)

您可以使用MySQL的CONCAT:

$pdo = $db->prepare('SELECT *,
CONCAT(s.firstname, ' ', s.name) AS teacher
FROM projects pj
LEFT JOIN school s ON pj.teacher=s.id 
WHERE project_id = :project_id ');  

$pdo->execute(array('project_id' => $project_id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    echo $row["teacher"];
}