簡體   English   中英

MySQL-選擇一個值(如果它存在於表1中),否則,從表2中選擇它

[英]Mysql - Select a value if it exists in table1, otherwise if it doesn't, select it from table2

我有兩個表(table1和table2)。 如果用戶名存在於表之一中,我想從table1或table2中選擇用戶密碼。

另外,假設用戶名對於兩個表都是唯一的,因此不會有任何重復。

須藤代碼

SELECT table1.password 
  FROM table1 
WHERE table1.username = ?

OR #(if not found)

SELECT table2.password
  FROM table2
WHERE table2.username = ?

野牌在哪里? =給定的用戶名。

我只希望返回一列帶有密碼值的列。

如果您確定用戶名對於兩個表都是唯一的,則可以使用union子句:

SELECT table1.password 
  FROM table1 
WHERE table1.username = ?

UNION

SELECT table2.password
  FROM table2
WHERE table2.username = ?

像這樣的東西只會在üassword中產生1行

SELECT result.password 
FROM (
        SELECT 1 AS id,table1.password 
        FROM table1 
        WHERE table1.username = ?
    UNION ALL
        SELECT 2,table2.password 
        FROM table2 
    WHERE table2.username = ?
) AS result 
ORDER BY id
LIMIT 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM