MySQL离开了连接查询

时间:2012-07-19 23:18:47

标签: mysql

我的数据库中有一个关系表,它有四个值AKA ...

id, int, primary, auto-incriment 
mem1, int
mem2, int
type, enum('a','b')

我还有另一个包含成员id,username,firstname和lastname

的表

我想点击一个按钮,无需重复即可获得两个人之间的关系。 这是我到目前为止的查询...

SELECT 
    myMembers.id AS id, 
    myMembers.username AS username, 
    myMembers.firstname AS firstname,
    myMembers.lastname AS lastname 
FROM myMembers 
INNER JOIN memberRelations 
    ON memberRelations.mem2=myMembers.id
WHERE memberRelations.mem1='$id' OR memberRelations.mem2='$id' ORDER BY myMembers.username 
ASC

这里的问题是,在某些用户上它给了我正确的值,但在其他用户上它给了我配置文件用户而不是其他成员关系。我怀疑这与查询的ON部分有关,但实际上我迷路了!有没有更好的方法来实现我的目标?或者我可以在查询中更正一些内容吗?任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

根据您的问题,我认为您需要选择以下两种关系成员的以下内容:

SELECT
    R.type,
    M1.id AS id1, 
    M1.username AS username1, 
    M1.firstname AS firstname1,
    M1.lastname AS lastname1,
    M2.id AS id1, 
    M2.username AS username2, 
    M2.firstname AS firstname2,
    M2.lastname AS lastname2
FROM memberRelations AS R
       INNER JOIN myMembers AS M1 ON R.mem1=M1.id
       INNER JOIN myMembers AS M2 ON R.mem2=M2.id
WHERE R.mem1='$id' OR R.mem2='$id'