来自连接的MySQL连接和子查询

时间:2012-03-29 05:51:11

标签: sql join subquery

这是my earlier question的后续内容:

SELECT s.unique_id, s.counter, s.sequence_length, s.yearmonth, s.mod_date_stamp,
  pg1.page_url as page1, pg2.page_url as page2, pg3.page_url as page3,
  pg4.page_url as page4, pg5.page_url as page5
FROM session s
  LEFT JOIN sessionpage pg1 ON pg1.unique_id = s.page1 
  LEFT JOIN sessionpage pg2 ON pg2.unique_id = s.page2
  LEFT JOIN sessionpage pg3 ON pg3.unique_id = s.page3
  LEFT JOIN sessionpage pg4 ON pg4.unique_id = s.page4
  LEFT JOIN sessionpage pg5 ON pg5.unique_id = s.page5

可以正常显示整个表格。现在,我需要select s.unique_id WHERE page1=/path/to/something.html AND page2=/path/to/somethingelse.html

我无法弄清楚如何在不返回整个表的情况下仅返回unique_id。我知道我需要一个嵌套查询,但我无法弄清楚语法。

它应该类似于:

SELECT s.unique_id 
  (SELECT pg1.page_url as page1, pg2.page_url as page2, pg3.page_url as page3,
    pg4.page_url as page4, pg5.page_url as page5 FROM session201203) s
  LEFT JOIN sessionpage pg1 ON pg1.unique_id = s.page1 
  LEFT JOIN sessionpage pg2 ON pg2.unique_id = s.page2 
  LEFT JOIN sessionpage pg3 ON pg3.unique_id = s.page3 
  LEFT JOIN sessionpage pg4 ON pg4.unique_id = s.page4 
  LEFT JOIN sessionpage pg5 ON pg5.unique_id = s.page5
WHERE s.sequence_length = 2 AND s.page1 = '/path1.html' AND s.page2 = '/path2.html';

但是这个查询失败了,因为它尝试在加入之前找到pg1等。我尝试了很多东西,无法弄明白。再次感谢。

1 个答案:

答案 0 :(得分:0)

尝试此操作:在最后一次加入后移动括号) s

SELECT s.unique_id 
  FROM (SELECT pg1.page_url as page1, pg2.page_url as page2, pg3.page_url as page3,
    pg4.page_url as page4, pg5.page_url as page5 FROM session201203
  LEFT JOIN sessionpage pg1 ON pg1.unique_id = s.page1 
  LEFT JOIN sessionpage pg2 ON pg2.unique_id = s.page2 
  LEFT JOIN sessionpage pg3 ON pg3.unique_id = s.page3 
  LEFT JOIN sessionpage pg4 ON pg4.unique_id = s.page4 
  LEFT JOIN sessionpage pg5 ON pg5.unique_id = s.page5) s
WHERE s.sequence_length = 2 AND s.page1 = '/path1.html' AND s.page2 = '/path2.html';