用mysql加入两个sql查询

时间:2013-06-26 19:01:42

标签: php mysql database

查询1

$query = "SELECT  match_id, match_date, home_team, 
    home_score, away_score, away_team, rating

              FROM premier_league2 
              WHERE (home_team ='" .$home_team ."'
              OR    away_team ='" .$home_team ."')  
              AND   postponed !=1
              AND   league =1
              AND   match_date <'" . $current_date ."'
              AND   match_date >'" . $newseason ."'
              ORDER BY match_date DESC LIMIT 1";

结果

676 2013-05-19  Newcastle Utd   0   1   Arsenal -14

查询2

SELECT home_per, draw_per, away_per FROM rating WHERE rating = -14;

结果

28.30 26.50 45.10 

现在我正在尝试加入这些查询,例如

676 2013-05-19  Newcastle Utd   0   1   Arsenal -14  28.30 26.50 45.10 

评分(-14)在两个表中都很常见,寻求你的帮助。

2 个答案:

答案 0 :(得分:2)

你可以通过加入来实现。

SELECT 
    a.match_id, a.match_date, a.home_team, a.home_score, a.away_score, a.away_team, a.reting, b.home_per, b.draw_per, b.away_per 
FROM
    premier_league2 a
LEFT JOIN 
    rating b ON a.rating = b.rating
WHERE 
    (home_team = %HOME_TEAM%
    OR    away_team = %HOME_TEAM%)  
    AND   postponed !=1
    AND   league =1
    AND   match_date < %SURRENT_DATE%
    AND   match_date > %NEW_SEASON%
    ORDER BY match_date DESC LIMIT 1)

Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

答案 1 :(得分:2)

SELECT
   pl.match_id, pl.match_date, pl.home_team, 
    pl.home_score, pl.away_score, pl.away_team, pl.rating,
   r.home_per, r.draw_per, r.away_per
FROM
   premier_league2 pl
 INNER JOIN rating as r ON pl.rating = r.rating
WHERE
(pl.home_team ='" .$home_team ."'
              OR    pl.away_team ='" .$home_team ."')  
              AND   pl.postponed !=1
              AND   pl.league =1
              AND   pl.match_date <'" . $current_date ."'
              AND   pl.match_date >'" . $newseason ."'
              ORDER BY pl.match_date DESC LIMIT 1";