MySql选择JOIN问题。只是不知道该怎么做

时间:2011-10-06 20:03:54

标签: php mysql

我有2个表格(如图所示),第一个是页面表(cvl_pages),第二个是mysettings表。

在我的设置表格中,您会看到以下列:fav1fav2fav3fav4fav5fav6 - - 这些字段中的整数对应于Page_ID表中的cvl_pages

我正在尝试编写一个select语句,从Page_ID表中选择Page_Titlefunctioncvl_pages WHERE PAGE_ID = fav 1到6 。

然后我需要为与fav1fav2fav3 ...等对应的页面标题/功能创建变量。

我很难把它放在脑海里......没有为每个“fav”创建一个单独的SELECT语句

我想我要求帮助创建一个select语句,它将为每个fav字段提供正确的页面标题和功能。

enter image description here

enter image description here

感谢!!!!

3 个答案:

答案 0 :(得分:1)

您必须加入每个不同的收藏夹,但您可以在一个查询中执行此操作:

select 
  s.*, /* or more specific fields you need from s */
  f1.Page_Title as Page_Title1,
  f1.function as function1,
  f2.Page_Title as Page_Title2,
  f2.function as function2,
  f3.Page_Title as Page_Title3,
  f3.function as function3,
  f4.Page_Title as Page_Title4,
  f4.function as function4,
  f5.Page_Title as Page_Title5,
  f5.function as function5,
  f6.Page_Title as Page_Title6,
  f6.function as function6
from 
  mysettings s
  inner join cvl_pages f1 on f1.Page_Id = s.fav1
  inner join cvl_pages f2 on f2.Page_Id = s.fav2
  inner join cvl_pages f3 on f3.Page_Id = s.fav3
  inner join cvl_pages f4 on f4.Page_Id = s.fav4
  inner join cvl_pages f5 on f5.Page_Id = s.fav5
  inner join cvl_pages f6 on f6.Page_Id = s.fav6

答案 1 :(得分:0)

为什么不能进行简单的加入?类似的东西:

SELECT Page_ID, Page_Title FROM cvl_pages p join mysettings s 
    on p.Page_ID in (s.fav1, s.fav2, s.fav3, s.fav4, s.fav5, s.fav6)
    where s.User_ID = 43;

答案 2 :(得分:0)

在这种情况下,您应该使用GolezTrol的答案,但使用LEFT JOIN而不是Inner Join:

SELECT settings.User_ID, 
  f1.Page_ID as Page_ID1, f1.Page_Title as Page_Title1,
  f2.Page_ID as Page_ID2, f2.Page_Title as Page_Title2,
  f3.Page_ID as Page_ID3, f3.Page_Title as Page_Title3,
  f4.Page_ID as Page_ID4, f4.Page_Title as Page_Title4,
  f5.Page_ID as Page_ID5, f5.Page_Title as Page_Title5,
  f6.Page_ID as Page_ID6, f6.Page_Title as Page_Title6,
  FROM mysettings s 
    left join cvl_pages f1 on s.fav1 = f1.Page_ID
    left join cvl_pages f2 on s.fav2 = f2.Page_ID
    left join cvl_pages f3 on s.fav3 = f3.Page_ID
    left join cvl_pages f4 on s.fav4 = f4.Page_ID
    left join cvl_pages f5 on s.fav5 = f5.Page_ID
    left join cvl_pages f6 on s.fav6 = f6.Page_ID
  where s.User_ID = 43;