3

我在 Mysql DB 表中有以下表结构:Mytable

--------------------------------
| uid | locationid | projectid |
--------------------------------
|  2  |      4     |    2     | 
|  2  |      4     |    2     | 
|  2  |      3     |    5     | 
|  2  |      3     |    5     | 
|  2  |      1     |    2     | 
|  2  |      1     |    2     | 
|  2  |      1     |    2     | 
|  2  |      1     |    1     | 
|  3  |      1     |    5     | 
|  3  |      1     |    2     | 
|  3  |      1     |    1     | 
|  3  |      1     |    1     | 
|  7  |      3     |    1     | 
|  5  |      1     |    5     | 
|  6  |      4     |    2     | 
|  5  |      1     |    5     | 
|  3  |      4     |    1     | 
|  3  |      3     |    3     | 
|  7  |      4     |    2     | 
|  7  |      4     |    3     | 

假设我通过了 uid=2 那么对于 uid=2 locationid 和 projectid 的唯一组合是这样的

|  2  |      4     |    2     | 
|  2  |      3     |    5     | 
|  2  |      1     |    2     | 
|  2  |      1     |    1     | 

现在我想要所有具有上述 locationid 和 projectid 组合的 uid 匹配。意味着结果应该是

|  3  |      1     |    2     | 
|  3  |      1     |    1     | 
|  3  |      1     |    1     | 
|  6  |      4     |    2     | 
|  7  |      4     |    2     | 

如果我通过 uid=3 那么结果应该是

|  2  |      1     |    2     | 
|  2  |      1     |    2     | 
|  2  |      1     |    2     | 
|  2  |      1     |    1     | 
|  5  |      1     |    5     | 
|  5  |      1     |    5     | 

为此,我使用了以下查询,但它给出了错误的结果,因为 locationid 和 projectid 组合不正确匹配

 SELECT a.*
 FROM Mytable a, Mytable b 
 WHERE a.locationid = b.locationid
 AND a.projectid = b.projectid
 AND a.locationid IN (SELECT DISTINCT locationid FROM Mytable WHERE uid=$pmid)
 AND a.projectid IN(SELECT DISTINCT projectid FROM Mytable WHERE uid=$pmid)
 AND a.uid !=$pmid

这里 $pmid 是我传递的 uid 值。我的查询有什么问题?我的查询是否正确?请帮我。

提前致谢。

4

3 回答 3

2

这应该有效:

SELECT a.*
FROM Mytable a
     INNER JOIN (SELECT DISTINCT locationid, projectid
                 FROM   Mytable
                 WHERE  uid = 2
                ) b
        ON a.locationid = b.locationid
           AND a.projectid = b.projectid
           AND a.uid <> 2;

示例:SQLFiddle

于 2012-09-06T06:01:55.713 回答
0

尝试这个:

SELECT t.* 
FROM   Mytable t
JOIN
       ( SELECT distinct locationid , projectid
         FROM Mytable
         WHERE uid=<uid>)a
ON     t.locationid =a.locationid 
AND    t.projectid=a.projectid
WHERE  t.uid != <uid>
于 2012-09-06T06:02:51.477 回答
0

试试这个查询 -

SELECT t1.* FROM mytable t1
  JOIN (SELECT * FROM mytable WHERE uid = 2 GROUP BY locationid, projectid) t2
    ON t1.uid <> t2.uid AND
       t1.locationid = t2.locationid AND
       t1.projectid = t2.projectid;

指定您的uidin WHERE 子句(第二行)。

于 2012-09-06T06:10:50.870 回答