注意:以下資訊僅出于教育目的而人為創建。
假設以下查詢:
SELECT author, is_public, content FROM dapp.messages WHERE is_public = '0'
得到下表:
| author| is_public | content |
-----------------------------------------------
| 3240 |0 |Hello, I'm Bertha |
| 4039 |0 |Hello, I'm Kristina |
| 4810 |0 |Hello, I'm April |
現在,在這種情況下,列author中的數字鏈接到另一個名為 的表中的一行credentials,這意味著:
3240鏈接到credentials表中的這一行:
| id | first_name | member_type |
----------------------------------------
| 3240 |Bertha | regular |
4039鏈接到credentials表中的這一行:
| id | first_name | member_type |
----------------------------------------
| 4039 |Kristina | regular |
4810鏈接到credentials表中的這一行:
| id | first_name | member_type |
----------------------------------------
| 4039 |April | regular |
所以,我想知道將表中的first name列添加credentials到本文中第一個查詢獲得的表中的正確方法,最終得到如下輸出:
| author| is_public | content | first_name |
--------------------------------------------------------------
| 3240 |0 |Hello, I'm Bertha |Bertha |
| 4039 |0 |Hello, I'm Kristina |Kristina |
| 4810 |0 |Hello, I'm April |April |
作為一個新手,我認為通過嘗試以下查詢,我會從上面得到所需的輸出:
SELECT t1.*, t2.*
FROM ( SELECT author, is_public, content FROM dapp.messages WHERE is_public = '0')
t1 CROSS JOIN ( SELECT first_name FROM dapp.credentials WHERE id IN (SELECT author FROM dapp.messages)) t2
但我最終創建了一個拋出這個輸出的怪物:
| author| is_public | content | first_name |
--------------------------------------------------------------
| 3240 |0 |Hello, I'm Bertha |Bertha |
| 3240 |0 |Hello, I'm Bertha |Kristina |
| 3240 |0 |Hello, I'm Bertha |April |
| 4039 |0 |Hello, I'm Kristina |Bertha |
| 4039 |0 |Hello, I'm Kristina |Kristina |
| 4039 |0 |Hello, I'm Kristina |April |
| 4810 |0 |Hello, I'm April |Bertha |
| 4810 |0 |Hello, I'm April |Kristina |
| 4810 |0 |Hello, I'm April |April |
我根本沒有得到,所以我被困在這里。
uj5u.com熱心網友回復:
我不確定你為什么認為你需要一個交叉連接,看起來你需要一個簡單的內部連接:
select m.author, m.is_public, m.content, c.first_name
from dapp.messages m
join dapp.credentials c on c.id = m.author
where m.is_public = '0';
由于您想要單個列,因此相關子查詢也是一個可行的選擇:
select m.author, m.is_public, m.content,
(select first_name from dapp.credentials c where c.id = m.author) as first_name
from dapp.messages m
where m.is_public = '0';
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/438426.html
上一篇:swift中的“自我”是什么?
