2012-11-13 71 views
4
$sql = "SELECT events.*, leagues.lname as leagueName,leagues.aliasname as AliasName, t1.tname as team1_name, t2.tname as team2_name 
FROM events 
INNER JOIN leagues ON events.leagueid = leagues.id 
INNER JOIN teams AS t1 ON events.teamhid = t1.teamid 
INNER JOIN teams AS t2 ON events.teamaid = t2.teamid 
WHERE sdate='1352835000' "; 

它給表使用附加凡在SQL INNER JOIN

id sdate ... leagueName AliasName team1_name team2_name 

我怎麼能添加附加條件:

WHERE AliasName LIKE 'word' AND (team1_name LIKE 'word2' OR team2_name LIKE 'word3') 

回答

2

不能使用列ALIAS這是與內聯)where條款,所以在你的情況下,你需要使用tableName.columnName除了在子查詢其包裝)

WHERE leagues.aliasname LIKE 'word' AND 
    (t1.tname LIKE 'word2' OR t2.tname LIKE 'word3') 

爲什麼你不能使用的原因是因爲查詢的執行順序如下

  • FROM子句(你可以在這裏設置表的別名)
  • WHERE子句
  • GROUP BY子句
  • HAVING子句
  • SELECT子句(COLUMN這裏化名)
  • ORDER BY子句
+1

+1的訂貨! – nawfal

1

像這樣:

SELECT * 
FROM 
(
    SELECT 
     events.*, 
     leagues.lname as leagueName, 
     leagues.aliasname as AliasName, 
     t1.tname as team1_name, 
     t2.tname as team2_name 
    FROM events 
    INNER JOIN leagues ON events.leagueid = leagues.id 
    INNER JOIN teams AS t1 ON events.teamhid = t1.teamid 
    INNER JOIN teams AS t2 ON events.teamaid = t2.teamid 
    WHERE sdate = '1352835000' 
) t 
WHERE AliasName LIKE 'word' 
    AND (team1_name LIKE 'word2' OR team2_name LIKE 'word3')