简体   繁体   English

MySQL 3列查询返回重复项

[英]MySQL 3 column query return duplicates

x_Id  | y_Id | z_Id
----- |----- |-----
1     | 1    | 1
2     | 1    | 1
3     | 1    | 1
4     | 1    | 1
5     | 1    | 1
1     | 2    | 3

I am relatively new at programming and I cant figure out this MySql query. 我在编程方面相对较新,我无法弄清楚这个MySql查询。 I need to select x_Id only where ((y_Id = 1 AND z_Id = 1) AND (y_Id = 2 AND z_Id = 3)). 我只需要在((y_Id = 1 AND z_Id = 1)AND(y_Id = 2 AND z_Id = 3))中选择x_Id。 Therefore, using these numbers as an example the only thing that should be selected is (x_Id =) 1. 因此,以这些数字为例,唯一应选择的是(x_Id =)1。

**All of these columns are in the same table **所有这些列都在同一表中

The closest I have come is by using this query: 我最接近的是使用此查询:

SELECT 
    * 
FROM 
    `relationships` 
WHERE
    y_id = 1 AND
    z_id = 1

UNION    
SELECT 
    * 
FROM 
    `relationships` 
WHERE
    z_id = 3 AND
    y_id = 2

However, this returns all the x_ids and x_id = 1 again as a duplicate. 但是,这将再次返回所有x_id和x_id = 1。

**I am using sqlPro and MySql 5 **我正在使用sqlPro和MySql 5

no need to Union. 无需联盟。

Updated after seeing comments: 看到评论后更新:

select
*
from relationships T1
INNER JOIN relationshipsT2 on t1.x_Id   = t2.x_Id  where
((T1.y_Id = 1 AND T1.z_Id = 1) AND (T2.y_Id  = 2 AND T2.zz_Id= 3))

also you can only return x_Id instead of * 你也只能返回x_Id而不是*

Updated after seeing comments: 看到评论后更新:

Using an aggregate SUM() you can total up the number of conditions met per value of x_id . 使用汇总SUM()您可以总计每个x_id值满足的条件数。 If the total is > 1, both conditions are met somewhere in the table. 如果总数> 1,则表中某处同时满足两个条件。

SELECT DISTINCT x_id FROM (
  SELECT
    x_id,
    SUMCASE WHEN (y_id = 1 AND z_id = 1) OR (z_id = 3 AND y_id = 2) THEN 1 ELSE 0 END) AS hasboth
  FROM relationships
  GROUP BY x_id
  HAVING hasboth > 1
) subq

If you are only interested in the x_id value you can use the query above, but just add DISTINCT and project only the x_id value. 如果只对x_id值感兴趣,则可以使用上面的查询,但是只需添加DISTINCT并仅投影x_id值即可。

Example: 例:

SELECT 
    DISTINCT x_id 
FROM 
 `relationships` 
WHERE
     y_id = 1 AND z_id = 1

UNION

SELECT 
    DISTINCT x_id 
FROM 
    `relationships` 
WHERE
    z_id = 3 AND y_id = 2

There are few other way how to do it, which are even easier such as use OR in the WHERE clause. 几乎没有其他方法可以做到,例如WHERE子句中的OR甚至更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM