I have 2 different tables, which have just one field with same name ('username'). They're not related each other. I need with just one query to select all the rows among them both which have this field equal to a given value.
I came up with this, which is off course wrong... SELECT * FROM user AS a FULL JOIN future_user AS b WHERE a.username=x OR b.username=x
These the tables I'm talking about:
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;
Use a UNION
:
SELECT
fields
FROM
user
WHERE
user.username=x
UNION
SELECT
fields
FROM
future_user
WHERE
future_user.username=x
Note that you can't do SELECT *
in either because they have different fields. You'll need to return the same fields from both subqueries.
It sounds like what you are looking for is a Full Outer Join . Some database systems (notably MySQL) do not support such joins. For those that do, your query would be something like:
SELECT * FROM user FULL OUTER JOIN future_user
ON user.username = future_user.username;
For those that don't, you will have to use a UNION of a LEFT JOIN and RIGHT JOIN as explained in the Wikipedia article linked above, something like (in 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;
You may want to serious consider if there is an alternative available, such as combining the tables or processing the resultsets from two separate queries on the back end. FULL OUTER JOINs are very weird to be using, and you're going to end up with a bunch of NULL field values that you'll have to check for and validate.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.