编写SQL查询时需要帮助

时间:2011-08-03 04:40:28

标签: mysql

我在Sopocosy运动饲料文档中找到了一个查询。我已更改此查询以满足我的需要。这是我的查询

SELECT
        e.id as eid,
        ts.name AS stage_name,
        DATE_FORMAT(e.startdate, '%d.%m.%Y') AS startdate,
        DATE_FORMAT(e.startdate, '%H:%i') AS starttime,
        MIN(IF( ep.number = 1, p.name, NULL)) AS home_team,
        IF(e.status_type = 'notstarted', '-',(MIN(IF(ep.number = 1, r.value, NULL)))) AS home_score,
        IF(e.status_type = 'notstarted', '-',(MIN(IF(ep.number = 2, r.value, NULL)))) AS away_score,
        MIN(IF(ep.number = 2, p.name, NULL)) AS away_team,
        es.name AS status_text
FROM
        tournament_template AS tt INNER JOIN
        tournament AS t ON t.tournament_templateFK = tt.id INNER JOIN
        tournament_stage AS ts ON t.id = ts.tournamentFK INNER JOIN
        event AS e ON ts.id = e.tournament_stageFK INNER JOIN
        event_participants AS ep ON e.id = ep.eventFK LEFT JOIN
        status_desc AS es ON e.status_descFK = es.id LEFT JOIN
        participant AS p ON ep.participantFK = p.id LEFT JOIN
        result AS r ON ep.id = r.event_participantsFK AND r.result_code = 'runningscore' LEFT JOIN
        property AS prop ON e.id = prop.objectFK AND prop.object ='event' AND prop.name = 'Live'
WHERE
        tt.sportFK = '1'
GROUP BY
        e.id
ORDER BY 
        ts.id, e.startdate, e.id

现在我的问题是 我可以在where子句中使用home_team和away_team吗?如果是,那么如何。从理论上讲,我想在where子句中使用它。

WHERE home_team ='Navibank Saigon'OR away_team ='Navibank Saigon';

但是它给出了Unknown Column错误。

请帮助

2 个答案:

答案 0 :(得分:1)

看起来p.namehome_team所返回内容的真正列名,因此请将WHERE子句设为

WHERE p.name = 'Navibank Saigon'

答案 1 :(得分:0)

您无法使用WHERE home_team = 'Navibank Saigon' OR away_team = 'Navibank Saigon'的原因是您在执行搜索查询后在结果集上指定了这些“列名称”(别名)。 WHERE语句是搜索查询的一部分,需要真正的列名,在本例中为p.name。另一方面,ORDER BY语句在结果集上执行,因此可以使用像'home_team'这样的列别名。

对于查询部分:您在GROUP BY语句中使用聚合函数(MIN)中的两个团队。必须使用HAVING而不是WHERE来过滤GROUP BY语句。

这导致:

GROUP BY
   e.id
HAVING
   MIN(IF( ep.number = 1, p.name, NULL)) = 'Navibank Saigon'
       OR MIN(IF( ep.number = 1, p.name, NULL)) = 'Navibank Saigon'