2012-11-01 93 views
2

我試圖想出一個查詢,其中第三個表格將加入另外兩個表格。問題是這個第一個表有不同版本,我需要查詢來查看錶1中的列,然後選擇正確的表來加入,但生成的查詢必須返回表1中的所有行,只需加入一個額外的表3符合WHERe條款的特定行。 這甚至可能嗎?根據第一個表格的內容加入表格

實施例:

表1 =用戶

表2 =橫幅

表3 = UserSettings OR AdminSettings或全無

查詢會說...

WHERE User.rank='admin' LEFT JOIN AdminSettings 

WHERE User.rank='user' LEFT JOIN UserSettings 

我當前的查詢是這樣的:

$query = "SELECT * FROM Users as U WHERE U.user_id = :id "; 
$query .= "LEFT JOIN Banners as B ON U.banner_id = B.banner_id "; 
$query .= "LEFT JOIN AdminSettings ON U.server_id = AdminSettings.user_id WHERE U.rank='Admin' "; 
$query .= "LIMIT 1"; 

問題是,它只能說明有User.rank =「管理員」行不顯示行,其中User.rank =「用戶」休息。

回答

2

嘗試在字段列表中使用IF子句,像這樣中使用CASE

$query = "SELECT field1, field2, field3, IF(User.rank = 'admin', A.field, B.field)"; 
$query .= " FROM Users as U"; 
$query .= " LEFT JOIN Banners as B ON U.banner_id = B.banner_id"; 
$query .= " LEFT JOIN AdminSettings as A ON U.server_id = A.user_id"; 
$query .= " LIMIT 1"; 

類似的東西應該做的伎倆。

3

加入table3兩次,select語句

SELECT a.*, 
     b.* 
     CASE WHEN a.rank = 'admin' 
      THEN c.user_ID      -- gets value from AdminSettings 
      ELSE d.user_ID      -- gets value from UserSettings 
     END as ColName1, 
     CASE WHEN a.rank = 'admin' 
      THEN c.colName      -- gets value from AdminSettings 
      ELSE d.colName      -- gets value from UserSettings 
     END as ColName2 
FROM users a 
     INNER JOIN banners b 
      ON a.banner_id = b.banner_id 
     LEFT JOIN AdminSettings c 
      ON a.server_ID = c.user_ID 
     LEFT JOIN UserSettings d 
      ON a.server_ID = d.user_ID 
相關問題