搜索所有表

时间:2015-06-11 07:16:43

标签: php mysql sql

我有一点问题。我的数据库中有2个表:

servico,id,nome,profissao(水管工,电工,电子),数据和本地。

canalizador,包含id,nome,profissao(仅限管道工),数据和本地。

我有这个代码,以便我可以访问“canalizador”表:

mysql_connect($host,$user,$passwd) or die (mysql_error());
mysql_select_db($database);

$query = "SELECT * FROM canalizador WHERE profissao LIKE '$profissao'";
$result = mysql_query($query) or die(mysql_error());
$casaArray = array();

但我需要一个代码,只需按下菜单中每个职业的按钮(profissao),我就可以搜索所有表格,例如“canalizador”表。如果我这样做:

mysql_connect($host,$user,$passwd) or die (mysql_error());
mysql_select_db($database);

$query = "SELECT * FROM canalizador, carpinteiro WHERE profissao LIKE '$profissao'";
$result = mysql_query($query) or die(mysql_error());
$casaArray = array();

我有这个错误:

  

where子句中的'profissao'列是不明确的

4 个答案:

答案 0 :(得分:2)

使用两个表执行LIKE,在结果中使用select id, nome, profissao, data, local from ( select id, nome, profissao, data, local from servico UNION ALL select id, nome, profissao, data, local from canalizador ) dt where dt.profissao LIKE '$profissao' (作为派生表):

UNION ALL

或者,正如AsConfused所建议的,只需select id, nome, profissao, data, local from servico where profissao LIKE '$profissao' UNION ALL select id, nome, profissao, data, local from canalizador where profissao LIKE '$profissao'

{{1}}

答案 1 :(得分:0)

试试这个:

mysql_connect($host,$user,$passwd) or die (mysql_error());
mysql_select_db($database);

$query = "SELECT * FROM canalizador c1, carpinteiro c2 WHERE c1.profissao LIKE '$profissao'";
                                                          // ^ c1 or c2 
$result = mysql_query($query) or die(mysql_error());
$casaArray = array();

答案 2 :(得分:0)

首先,使用逗号分隔的表是不好的做法:

SELECT * FROM canalizador, carpinteiro, etc...

您需要使用JOINS并在SELECT子句中列出列名,如下所示:

SELECT col1, col2, col3 
FROM canalizador can 
JOIN carpinteiro car ON can.Id = car.Id 

然后指定您要使用哪个表格profissao

WHERE can.profissao LIKE '$profissao

答案 3 :(得分:0)

作为第一个选项,您可以使用AS关键字为列名称指定别名,即:

SELECT canalizador.column AS col1, carpinteiro.column AS col2 
FROM canalizador, carpinteiro WHERE profissao LIKE '$profissao'

作为第二个选项,您可以重新编写SQL查询并使用MySQL JOIN组合多个表结果,详细了解如何连接表here和更多常规信息here