2016-09-15 209 views
1

我在数据库表中搜索包含“un”的单词。 如何在输出$ data中获得两个行数据?组合mysql查询结果

实施例:

col1 | col2 


tom -------- unfriendly 

train ------- fast 

unused--- cloth 

$query = mysql_query("SELECT * FROM table 
WHERE col1 LIKE '%un%' 
OR col2 LIKE '%un%' 
ORDER BY col1 ASC"); 
while ($row = mysql_fetch_array($query)) { 
    $data[] = $row['col1']; 
} 

我从上面的代码中得到$ data = [tom,unused]。 我怎样才能得到$ data = [tom友好,未使用 - 布]?

回答

0

尝试使用CONCAT

SELECT CONCAT(col1, ' - ', col2) AS result 
FROM table 
WHERE col1 LIKE '%un%' OR 
     col2 LIKE '%un%' 
ORDER BY col1 ASC 

然后你就可以访问结果通过在你的PHP代码中设置:

while ($row = mysql_fetch_array($query)) { 
    $data[] = $row['result']; 
} 
+0

信誉太低。在未来 – askseekknock

1

正如@TimBegeleisen说,你可以在你的SQL请求中使用CONCAT,但你也可以Concat的字符串,你在你的PHP代码:

$query = mysql_query("SELECT * FROM table 
WHERE col1 LIKE '%un%' 
OR col2 LIKE '%un%' 
ORDER BY col1 ASC"); 
while ($row = mysql_fetch_array($query)) { 
    $data[] = $row['col1'] . ' - ' . $data['col2']; 
} 
+0

你的答案也可以工作,但后来发现并包含错字。 – askseekknock

+0

该死的你错字! – roberto06

+0

Upvoted是一个不错的选择。看到两种方法中的哪一种在大数据集上实际运行速度会很有趣。 –