MySql,内连接查询,必须匹配多行

时间:2012-01-05 09:47:58

标签: mysql sql inner-join

我正在创建一个MySQL查询,我想检索一个ID,但前提是我在查询中指定的所有行中都找到了匹配项。

Table: view_layout_rows

ID    owner    rows
___________________
49    1        2
50    1        2




Table: view_layout_rows_columns

ID    row    columns
___________________
49    1      5
49    2      4
50    1      5
50    2      5



SELECT vlr.id
FROM view_layout_rows vlr
INNER JOIN view_layout_rows_columns vlrc
ON vlr.id = vlrc.id 
WHERE vlr.rows = 2
AND (vlr.owner = 0 OR vlr.owner = 1)

并且应满足以下所有条件:

(vlrc.row = 1 AND vlrc.columns = 5) 
(vlrc.row = 2 AND vlrc.columns = 5)

只应返回ID 50。不应该返回49,因为它只满足最后两个条款中的第一个。

我怎么能这样做? (请注意,我之前问过这个问题,但我的要求不清楚。第二次尝试。) 提前感谢任何建议。

2 个答案:

答案 0 :(得分:6)

双重加入救援! : - )

SELECT vlc.* 
FROM view_layout_rows vlc
INNER JOIN view_layout_rows_columns vlrc1 ON vlrc1.id = vlc.id
INNER JOIN view_layout_rows_columns vlrc2 ON vlrc2.id = vlc.id
WHERE vlrc1.row = 1 AND vlrc1.columns = 5
  AND vlrc2.row = 2 AND vlrc2.columns = 5

  /* imported from original query */
  AND vlr.rows = 2
  AND (vlr.owner = 0 OR vlr.owner = 1);

答案 1 :(得分:0)

每个表的单一访问权限:

select r.*
from view_layout_rows r
join (select id, count(*) rec_count
      from view_layout_rows_columns
      where row in (1,2) and
            columns = 5
      group by id
      having count(*) = 2) c
on r.id = c.id
where r.rows = 2 and
      r.owner in (0,1)