我有两个不同的表,它们只有一个具有相同名称的字段('username')。他们彼此没有关系。我只需要一个查询就可以选择其中包含此字段等于给定值的所有行。
我想出了这个,当然错了...... SELECT * FROM user AS a FULL JOIN future_user AS b WHERE a.username = x OR b.username = x
我正在谈论的这些表格:
CREATE TABLE user
(
uid mediumint(6) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(15) NOT NULL,
password varchar(15) BINARY NOT NULL,
mail varchar(50) NOT NULL,
name varchar(50) NOT NULL,
surname varchar(50) NOT NULL,
birth char(10) NOT NULL,
sex tinyint(1) unsigned NOT NULL default 1,
address varchar(50) NOT NULL,
city varchar(50) NOT NULL,
zip char(5) NOT NULL,
province varchar(50) NOT NULL,
country tinyint(3) NOT NULL,
number1 varchar(50) NOT NULL,
number2 varchar(50) NOT NULL,
last_login TIMESTAMP,
registered TIMESTAMP,
online tinyint(1) unsigned default 0,
admin tinyint(1) unsigned default 0,
comment_allowed tinyint(1) unsigned default 0,
post_allowed tinyint(1) unsigned default 0
) ENGINE=InnoDB;
CREATE TABLE future_user
(
username varchar(15) NOT NULL,
password varchar(15) BINARY NOT NULL,
mail varchar(50) NOT NULL,
name varchar(50) NOT NULL,
surname varchar(50) NOT NULL,
birth char(8) NOT NULL,
sex tinyint(1) unsigned NOT NULL,
address varchar(50) NOT NULL,
city varchar(50) NOT NULL,
zip char(10) NOT NULL,
province varchar(50) NOT NULL,
country varchar(50) NOT NULL,
number1 varchar(50) NOT NULL,
number2 varchar(50) NOT NULL,
code char(10) NOT NULL
) ENGINE=InnoDB;
答案 0 :(得分:5)
使用UNION
:
SELECT
fields
FROM
user
WHERE
user.username=x
UNION
SELECT
fields
FROM
future_user
WHERE
future_user.username=x
请注意,您无法执行SELECT *
,因为它们具有不同的字段。您需要从两个子查询返回相同的字段。
答案 1 :(得分:0)
听起来你正在寻找的是Full Outer Join。某些数据库系统(尤其是MySQL)不支持此类连接。对于那些,您的查询将是这样的:
SELECT * FROM user FULL OUTER JOIN future_user
ON user.username = future_user.username;
对于那些不这样做的人,你将不得不使用LEFT JOIN和RIGHT JOIN的UNION,如上面链接的维基百科文章中所述,类似于(在MySQL中):
SELECT * FROM user LEFT JOIN future_user
ON user.username = future_user.username
UNION
SELECT * FROM user RIGHT JOIN future_user
ON user.username = future_user.username;
您可能需要认真考虑是否有可用的替代方法,例如组合表或处理后端上两个单独查询的结果集。 FULL OUTER JOIN使用非常奇怪,你最终会得到一堆NULL字段值,你必须检查和验证。