INNER JOIN同桌

时间:2013-02-10 10:24:24

标签: mysql sql join self-join

我试图从同一个表中获取一些行。这是一个用户表:用户有user_iduser_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]

但它没有显示结果。我想显示用户记录及其父记录。

6 个答案:

答案 0 :(得分:31)

我认为问题出在您的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

答案 1 :(得分:2)

您也可以使用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]

答案 2 :(得分:1)

也许这应该是选择(如果我理解正确的话)

select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before

答案 3 :(得分:1)

您的查询应该可以正常工作,但您必须使用别名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];

答案 4 :(得分:1)

我不知道如何创建表格,但试试这个......

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

答案 5 :(得分:1)

让我们尝试用一个简单明了的方案回答这个问题,包括3个 MySQL 表格,即日期表 colortable jointable

首先 查看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 primary key已分配到column <强> colorid

mysql> select * from colortable;
+---------+------------+
| colorid | colorvalue |
+---------+------------+
|      11 | blue       |
|      12 | yellow     |
+---------+------------+
2 rows in set (0.00 sec)

我们的最终 第三 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)

希望,这会对很多人有所帮助。