[英]INNER JOIN same table
我試圖從同一個表中獲取一些行。 它是一個用戶表:用戶有user_id
和user_parent_id
。
我需要獲取user_id
行和user_parent_id
行。 我編寫了這樣的代碼:
SELECT user.user_fname, user.user_lname
FROM users as user
INNER JOIN users AS parent
ON parent.user_parent_id = user.user_id
WHERE user.user_id = $_GET[id]
但它沒有顯示結果。 我想顯示用戶記錄及其父記錄。
我認為問題出在你的JOIN
狀態。
SELECT user.user_fname,
user.user_lname,
parent.user_fname,
parent.user_lname
FROM users AS user
JOIN users AS parent
ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]
編輯 :如果有沒有父母的用戶,您應該使用LEFT JOIN
。
你也可以使用UNION
SELECT user_fname ,
user_lname
FROM users
WHERE user_id = $_GET[id]
UNION
SELECT user_fname ,
user_lname
FROM users
WHERE user_parent_id = $_GET[id]
也許這應該是選擇(如果我正確理解問題)
select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before
您的查詢應該可以正常工作,但您必須使用別名parent
來顯示父表的值,如下所示:
select
CONCAT(user.user_fname, ' ', user.user_lname) AS 'User Name',
CONCAT(parent.user_fname, ' ', parent.user_lname) AS 'Parent Name'
from users as user
inner join users as parent on parent.user_parent_id = user.user_id
where user.user_id = $_GET[id];
我不知道如何創建表但嘗試這個...
SELECT users1.user_id, users2.user_parent_id
FROM users AS users1
INNER JOIN users AS users2
ON users1.id = users2.id
WHERE users1.user_id = users2.user_parent_id
讓我們嘗試用一個簡單的方案回答這個問題,有3個MySQL
表,即日期表, colortable和jointable 。
首先看到table
日期 table
值, primary key
分配給column
dateid :
mysql> select * from datetable;
+--------+------------+
| dateid | datevalue |
+--------+------------+
| 101 | 2015-01-01 |
| 102 | 2015-05-01 |
| 103 | 2016-01-01 |
+--------+------------+
3 rows in set (0.00 sec)
現在移動到我們的第二個 table
值colortable分配給column
colorid的 primary key
:
mysql> select * from colortable;
+---------+------------+
| colorid | colorvalue |
+---------+------------+
| 11 | blue |
| 12 | yellow |
+---------+------------+
2 rows in set (0.00 sec)
我們的最終第三個 table
連接 table
沒有 primary keys
,值為:
mysql> select * from jointable;
+--------+---------+
| dateid | colorid |
+--------+---------+
| 101 | 11 |
| 102 | 12 |
| 101 | 12 |
+--------+---------+
3 rows in set (0.00 sec)
現在我們的條件是找到dateid的 ,它們的顏色值都是藍色和黃色 。
所以,我們的查詢是:
mysql> SELECT t1.dateid FROM jointable AS t1 INNER JOIN jointable t2
-> ON t1.dateid = t2.dateid
-> WHERE
-> (t1.colorid IN (SELECT colorid FROM colortable WHERE colorvalue = 'blue'))
-> AND
-> (t2.colorid IN (SELECT colorid FROM colortable WHERE colorvalue = 'yellow'));
+--------+
| dateid |
+--------+
| 101 |
+--------+
1 row in set (0.00 sec)
希望,這會對很多人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.