在SQL INNER JOIN中使用其他WHERE

时间:2012-11-13 14:32:37

标签: mysql sql

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

它为TABLE提供 COLUMNS

id sdate ... leagueName AliasName team1_name team2_name 

我如何添加其他条件:

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

2 个答案:

答案 0 :(得分:2)

你不能使用{{1>}列(一致)ALIAS子句,所以在你的情况下你需要使用{{1 (除了将它包装在子查询中

where

您无法使用的原因是因为查询的执行顺序如下

  • FROM子句(您可以在此处设置TABLE别名
  • WHERE子句
  • GROUP BY子句
  • HAVING条款
  • SELECT子句( COLUMN alias here
  • ORDER BY子句

答案 1 :(得分: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')