x_Id | y_Id | z_Id
----- |----- |-----
1 | 1 | 1
2 | 1 | 1
3 | 1 | 1
4 | 1 | 1
5 | 1 | 1
1 | 2 | 3
我在编程方面相对较新,我无法弄清楚这个MySql查询。我只需要选择x_Id((y_Id = 1 AND z_Id = 1)AND(y_Id = 2 AND z_Id = 3))。 因此,使用这些数字作为示例,唯一应该选择的是(x_Id =)1。
**所有这些列都在同一个表中
我最接近的是使用此查询:
SELECT
*
FROM
`relationships`
WHERE
y_id = 1 AND
z_id = 1
UNION
SELECT
*
FROM
`relationships`
WHERE
z_id = 3 AND
y_id = 2
但是,这将再次返回所有x_ids和x_id = 1。
**我正在使用sqlPro和MySql 5
答案 0 :(得分:0)
无需联盟。
看到评论后更新:
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))
您也只能返回x_Id
而不是*
答案 1 :(得分:0)
使用汇总SUM()
,您可以累计每个值x_id
达到的条件数。如果总数> 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
答案 2 :(得分:0)
如果您只对x_id值感兴趣,可以使用上面的查询,但只需添加DISTINCT并仅投影x_id值。
示例:
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
除了WHERE子句中使用OR之外,还有其他一些方法可以做到更简单。