简体   繁体   中英

SQL Select AND OR

I have written an SQL query on a work bench that has the game details 100 different British football teams playing over a season. The team name, where the team is based, the dates on which the teams play games, the status of the team, etc are the attributes. In other words, the table would have rows that might look like this :

Liverpool FC, Liverpool, 2013-12-25, Professional 
Arsenal FC  , London   , 2013-10-18, Professional
Swindon FC  , Swindon  , 2013-12-25, Amateur

Now, these are just three teams, but my table has details of 100 teams and what I need to do is to find out the dates on which two teams (say, Liverpool and Swindon) BOTH play. In the rows above, you can see that Liverpool and Swindon BOTH play on 2013-12-25. I write my SQL query like so:

  SELECT date
  FROM footballclubs.tableofgames
  WHERE (team = 'Liverpool') AND (team='Swindon');

I am expecting the date 2013-12-25 to appear on the workbench, but all I get is blank. Can someone please tell me what I'm doing wrong? When I replace the word AND with the word OR, I get a long list of dates but that is NOT what I'm looking for. I'm looking for a date where BOTH Liverpool AND Swindon have played matches, so surely the word AND is required? Please help.

You need to join the table with itself to find all pairs of teams playing the same day, and then add the condition for your teams:

SELECT date
FROM footballclubs.tableofgames a 
    JOIN footballclubs.tableofgames b ON a.date=b.date
WHERE a.team='Liverpool' AND b.team='Swindon';

change your code this way:

SELECT g1.date
FROM footballclubs.tableofgames g1, footballclubs.tableofgames g2
WHERE (g1.team = 'Liverpool') AND (g2.team='Swindon') AND (g1.date=g2.date);

or more readable:

SELECT g1.date
FROM (SELECT date FROM footballclubs.tableofgames WHERE team='Liverpool') g1 
     INNER JOIN
     (SELECT date FROM footballclubs.tableofgames WHERE team='Swindon') g2
USING (date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM