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' ";

它给出了带有COLUMNS的 TABLE :

id sdate ... leagueName AliasName team1_name team2_name 

如何添加附加条件:

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

2 回答 2

2

您不能使用ALIAScolumn on (这是 in-line with )where子句,因此在您的情况下,您需要使用tableName.columnName(除了将其包装在子查询中)

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

不能使用的原因是因为查询的执行顺序如下

  • FROM 子句(您可以在此处设置 TABLE 别名
  • WHERE 子句
  • GROUP BY 子句
  • HAVING 子句
  • SELECT 子句(此处为 COLUMN 别名
  • ORDER BY 子句
于 2012-11-13T14:35:06.803 回答
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')
于 2012-11-13T14:35:11.190 回答