我有一点问题。我的数据库中有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'列是不明确的
答案 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)