473,726 Members | 2,262 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on a query to find all possible combinations of a set


Hi all!

For a match schedule I would like to find all possible combinations of
teams playing home and away (without teams playing to themselves of course).

I now the simple version works something like this:

For a (very) simple table containing three rows like this:

row 1: A
row 2: B
row 3: C

SELECT DISTINCT
t1.*, t2.* FROM t1, t1 as t2
WHERE
t1.id!=t2.id
ORDER BY
t1.id, t2.id;

would result in the following solution:

col1 col2
row1 A B
row2 A C
row3 B A
row4 B C
row5 C A
row6 C B

To find all the teams in a certain group I need to use the following query:

SELECT DISTINCT
team
FROM
program
WHERE
program.group = 'D2B'
AND (
id_season=IF(DA TE_FORMAT(CURRE NT_DATE(), '%m%d') >= '1101'
OR
DATE_FORMAT(CUR RENT_DATE(), '%m%d') < '0401' , 0, 4)
OR
id_season= IF(DATE_FORMAT( CURRENT_DATE(), '%m%d') >= '1101'
OR
DATE_FORMAT(CUR RENT_DATE(), '%m%d') < '0401' , 0,
IF(DATE_FORMAT( CURRENT_DATE(), '%m%d') > '0715', 1, 3))
);

As a relatively newbie on (my)SQL I am having trouble converting the
simple query stated above to a more extended one, that includes the last
query to find the teams in the group, for which I would like to find all
possible combinations of matches to be played.

I'm using MySQL 4.0.22 so I believe subqueries are not an option as I
can not upgrade to a newer version for the moment.

Can some one help me out? Thanks in advance!

Jonathan

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #1
3 7876
"Jonathan" <jo******@heela l.nl> wrote in message
news:d4******** **@reader08.wxs .nl...

For a match schedule I would like to find all possible combinations of
teams playing home and away (without teams playing to themselves of course).
I now the simple version works something like this:

For a (very) simple table containing three rows like this:

row 1: A
row 2: B
row 3: C

SELECT DISTINCT
t1.*, t2.* FROM t1, t1 as t2
WHERE
t1.id!=t2.id
ORDER BY
t1.id, t2.id;

would result in the following solution:

col1 col2
row1 A B
row2 A C
row3 B A
row4 B C
row5 C A
row6 C B

A few points here.

First, your DISTINCT clause is entirely unneccessary. You are using a cross
join to get every possible combination. This is an elegant and effective
method to get every possible combination. You will note that you get the
same results with and without the DISTINCT clause. This is because your
cross join already produces all unique (distinct!) combinations by design.

And you very neatly eliminate the situation of a team playing itself with
your WHERE exclusion. I might rewrite it something like this.

SELECT TeamsA.Team, TeamsB.Team
FROM tbl_Teams AS TeamsA, tbl_Teams As TeamsB
WHERE TeamsA.Team <> TeamsB.Team;

The DISTINCT clause is unneccessary and irreleveant here.

Okay - you may notice that you produce (TeamX vs. TeamY) as well as (TeamY
vs. TeamX). This is exactly what we expect from a cross join. A simple sql
solution to eliminate these redundant pairs does not come to (my limited!
:-) mind. I would resort to filtering these redundant pairs outside of
MySQL. Perhaps someone else can suggest a more elegant sql query solution.
To find all the teams in a certain group I need to use the following query:
SELECT DISTINCT
team
FROM
program
WHERE
program.group = 'D2B'
AND (
id_season=IF(DA TE_FORMAT(CURRE NT_DATE(), '%m%d') >= '1101'
OR
DATE_FORMAT(CUR RENT_DATE(), '%m%d') < '0401' , 0, 4)
OR
id_season= IF(DATE_FORMAT( CURRENT_DATE(), '%m%d') >= '1101'
OR
DATE_FORMAT(CUR RENT_DATE(), '%m%d') < '0401' , 0,
IF(DATE_FORMAT( CURRENT_DATE(), '%m%d') > '0715', 1, 3))
);

As a relatively newbie on (my)SQL I am having trouble converting the
simple query stated above to a more extended one, that includes the last
query to find the teams in the group, for which I would like to find all
possible combinations of matches to be played.
Your WHERE clause here is unnecessarily complex and most certainly
susceptible to simplification. Since I don't know how to divine your
intentions here, I can't make a suggestion other than to ask you to tell us
what you are trying to achieve.
I'm using MySQL 4.0.22 so I believe subqueries are not an option as I
can not upgrade to a newer version for the moment.


My standard workaround for dancing around the lack of subqueries is to use
temporary tables. You can always place "CREATE TEMPORARY TABLE {whatever}"
ahead of a SELECT query and then perform another query against your
temporary table. This is a *great* way to break a single complex query into
2 or more simpler queries. I actually prefer it to using subqueries which
only produces complicated, hard to debug code anyway. And - you have
TEMPORARY TABLES available to you with MySQL 4.0.22 .

Hope this is of some help
Thomas Bartkus

Jul 23 '05 #2
Thomas Bartkus wrote:
"Jonathan" <jo******@heela l.nl> wrote in message
news:d4******** **@reader08.wxs .nl...
For a match schedule I would like to find all possible combinations of
teams playing home and away (without teams playing to themselves of
course).

I might rewrite it something like this.

SELECT TeamsA.Team, TeamsB.Team
FROM tbl_Teams AS TeamsA, tbl_Teams As TeamsB
WHERE TeamsA.Team <> TeamsB.Team;

The DISTINCT clause is unneccessary and irreleveant here.

Okay - you may notice that you produce (TeamX vs. TeamY) as well as (TeamY
vs. TeamX). This is exactly what we expect from a cross join. A simple sql
solution to eliminate these redundant pairs does not come to (my limited!
:-) mind. I would resort to filtering these redundant pairs outside of
MySQL. Perhaps someone else can suggest a more elegant sql query solution.
I'm not bothered by the redundant pairs as all teams play both home and
away... so no need for filtering there.
To find all the teams in a certain group I need to use the following
query:
SELECT DISTINCT
team
FROM
program
WHERE
program.group = 'D2B'
AND (
id_season=IF(DA TE_FORMAT(CURRE NT_DATE(), '%m%d') >= '1101'
OR
DATE_FORMAT(CUR RENT_DATE(), '%m%d') < '0401' , 0, 4)
OR
id_season= IF(DATE_FORMAT( CURRENT_DATE(), '%m%d') >= '1101'
OR
DATE_FORMAT(CUR RENT_DATE(), '%m%d') < '0401' , 0,
IF(DATE_FORMAT( CURRENT_DATE(), '%m%d') > '0715', 1, 3))
);

As a relatively newbie on (my)SQL I am having trouble converting the
simple query stated above to a more extended one, that includes the last
query to find the teams in the group, for which I would like to find all
possible combinations of matches to be played.

Your WHERE clause here is unnecessarily complex and most certainly
susceptible to simplification. Since I don't know how to divine your
intentions here, I can't make a suggestion other than to ask you to tell us
what you are trying to achieve.


I know my where clause is a bit complex but unfortunately (IMHO)
neccesary to find the teams based on the league/competition they are
playing at this year.
All teams play an indoor ( id_season=2 ) and and outdoor competition.
The outdoor season is split into two seasons because of the bad weather
in our country ( The weather can be harsh, during this time the indoor
competition is played ).

Certain teams play against the same teams before and after the indoor
competition ( id_season=4), other teams play two separted outdoor
competitions with different teams in a group. The first season (
id_season=1 ) starts before the indoor competition and the second one
starts after the indoor competition ends ( id_season = 3 ). The last
group of leages plays against the same teams before and after the indoor
competition ( therefore there are more teams in those leagues ) and for
them id_season = 4.

I can give you a simplofoed query by evaluating the query for today
(because I don't have a table which group consists of which teams when)
I filter the database based on the id_season code as a team is either
playing the second half of their league (4) or playing the second league
for this group this year (3):

SELECT DISTINCT
team
FROM
program
WHERE
program.group = 'D2B'
AND
(
id_season= 4
OR
id_season= 3
)

Can you now (with the evaluated more simple query) help me join the two
queries together to find all the possible matches?

I was thinking somewhere along the line of this:

SELECT DISTINCT
teamsA.home as hometeam, teamsB.home as awayteam
FROM
program as teamsA, program As teamsB
WHERE
teamsA.group='D 2B' AND teamsB.group='D 2B'
AND
teamsA.home != teamsB.away
AND
(
(teamsA.id_seas on=3 or teamsA.id_seaso n=4)
AND
(teamsB.id_seas on=3 or teamsB.id_seaso n=4)
)
ORDER BY
hometeam, awayteam;

I'm hoping and guessing that there is some other and better way to do
this as I need to specify the criteria for both tables and have to use
the DISTINCT keyword as well to reduce the redundant records (7 fold
when the group consists of 8 teams).
I'm using MySQL 4.0.22 so I believe subqueries are not an option as I
can not upgrade to a newer version for the moment.

My standard workaround for dancing around the lack of subqueries is to use
temporary tables. You can always place "CREATE TEMPORARY TABLE {whatever}"
ahead of a SELECT query and then perform another query against your
temporary table. This is a *great* way to break a single complex query into
2 or more simpler queries. I actually prefer it to using subqueries which
only produces complicated, hard to debug code anyway. And - you have
TEMPORARY TABLES available to you with MySQL 4.0.22 .


Or is creating temporary tables the only solution? And if so: If I use
temporary tables are they deleted after closing the connection or do I
have to take care of that in my code?
Hope this is of some help
Thomas Bartkus


It certainly is... learned a lot!

Jonathan

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #3

"Jonathan" <jo******@heela l.nl> wrote in message
news:d4******** **@reader13.wxs .nl...
"Jonathan" <jo******@heela l.nl> wrote in message

I know my where clause is a bit complex but unfortunately (IMHO)
neccesary to find the teams based on the league/competition they are
playing at this year.
All teams play an indoor ( id_season=2 ) and and outdoor competition.
The outdoor season is split into two seasons because of the bad weather
in our country ( The weather can be harsh, during this time the indoor
competition is played ).

Certain teams play against the same teams before and after the indoor
competition ( id_season=4), other teams play two separted outdoor
competitions with different teams in a group. The first season (
id_season=1 ) starts before the indoor competition and the second one
starts after the indoor competition ends ( id_season = 3 ). The last
group of leages plays against the same teams before and after the indoor
competition ( therefore there are more teams in those leagues ) and for
them id_season = 4.

I can give you a simplofoed query by evaluating the query for today
(because I don't have a table which group consists of which teams when)
I filter the database based on the id_season code as a team is either
playing the second half of their league (4) or playing the second league
for this group this year (3):

SELECT DISTINCT
team
FROM
program
WHERE
program.group = 'D2B'
AND
(
id_season= 4
OR
id_season= 3
)
Slightly cleaner/leaner:
AND (id_season IN (3, 4))
Can you now (with the evaluated more simple query) help me join the two
queries together to find all the possible matches?

I was thinking somewhere along the line of this:

SELECT DISTINCT
teamsA.home as hometeam, teamsB.home as awayteam
FROM
program as teamsA, program As teamsB
WHERE
teamsA.group='D 2B' AND teamsB.group='D 2B'
AND
teamsA.home != teamsB.away
AND
(
(teamsA.id_seas on=3 or teamsA.id_seaso n=4)
AND
(teamsB.id_seas on=3 or teamsB.id_seaso n=4)
)
ORDER BY
hometeam, awayteam;

I'm hoping and guessing that there is some other and better way to do
this as I need to specify the criteria for both tables and have to use
the DISTINCT keyword as well to reduce the redundant records (7 fold
when the group consists of 8 teams).
Okay. I see now that you are drawing your team names from a table where any
single team may appear in more than one record. It seems you should have a
simple list of teams somewhere. No matter. You can get it on the fly.

CREATE TEMPORARY TABLE TeamList
SELECT DISTINCT home As TeamName
FROM program
WHERE (home.group = 'D2B')
AND (id_season IN (3,4));

Now you have a perfectly good table called "TeamList" with the names of all
teams in group 'D2B' with id_season = 3 or id_season = 4. The bulk of your
filtering is done.

SELECT HomeTeams.TeamN ame as HomeTeam,
AwayTeams.TeamN ame as AwayTeam
FROM TeamList As HomeTeams, TeamList As AwayTeams
ORDER BY HomeTeam, AwayTeam;

DROP TABLE TeamList;

That last DROP TABLE is not strictly necessary. Temporary tables are just
that - temporary. As soon as you close your connection, they disappear.
However, it is always good practice to deliberately DROP what you CREATE if
you don't want to keep something hanging around, even if the system is
friendly enough to do some of your housecleaning for you.
Or is creating temporary tables the only solution? That's doubtful. But -
I think it is the *cleanest* solution to compensate for the lack of nested
queries.
And
It is a great way to simplify some of the excruciatingly complicated queries
we all seem to blunder about with because you can use temporary tables to
bust them up into sequences of 2 or more simpler queries.
And if so: If I use
temporary tables are they deleted after closing the connection or do I
have to take care of that in my code?


Temporary tables disappear when you close your connection. Nevertheless,
you might find it useful (and professional!) to deliberately DROP the temp
table when you are done. If you try to re-execute your query inside the
same connection, you will find that the original table you created standing
in the way when you try to CREATE it again. By ending your code with a DROP
TABLE, you eliminate this problem.

One of the biggest learning hurdles that seems to keep people limited in
their sql coding abilities is the failure to view their sql code as a
*chain* of table transformations . TableA -> TableB -> TableC. Viewing it
in this way opens a lot of possibilities that many seem to miss. People
(myself included!) try to cram everything into a single, impossible to
decipher, statement. I blame MySQLs lack of stored procedures for this
situation. However, temporary tables provide an excellent remedy once you
discover how to use them.

Thomas Bartkus


Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
6021
by: hedylogus | last post by:
I've just begun learning C++ and I'm trying to write a program to shuffle a deck of cards. I've succeeded....for the most part....but every now and then rand() produces duplicate random numbers causing me to "lose" a card. How do I avoid this??? I've attached my code below for reference. Thanks in advance. ------------------------ #include <iostream> #include <cstdlib> #include <ctime>
4
1582
by: William D. Bartholomew | last post by:
We need to store land title information about properties in various Australian states, but each state maintains it's own land title registry and use different columns (well actually different combinations of the same columns). For example: Victoria store: TorrensUnit TorrensVolume TorrensFolio
3
6468
by: Tcs | last post by:
My backend is DB2 on our AS/400. While I do HAVE DB2 PE for my PC, I haven't loaded it yet. I'm still using MS Access. And no, I don't believe this is an Access question. (But who knows? I COULD be wrong... :) I've tried the access group...twice...and all I get is "Access doesn't like ".", which I know, or that my query names are too long, as there's a limit to the length of the SQL statement(s). But this works when I don't try to...
8
3724
by: Maxi | last post by:
There is a lotto system which picks 21 numbers every day out of 80 numbers. I have a table (name:Lotto) with 22 fields (name:Date,P1,P2....P21) Here is the structure and sample data: "Date","P1","P2","P3","P4","P5","P6","P7","P8","P9","P10","P11","P12","P13","P14","P15","P16","P17","P18","P19","P20","P21" 1/1/2005,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21 1/2/2005,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
6
2253
by: BerkshireGuy | last post by:
I need to create a query that will filter out records based on records. There can be many combinations depending of what the uses selects. For instance: Field: Telemed - This is a Y or N field. It is either a Telemed or it isnt.
17
2457
by: Carnosaur | last post by:
Hi all, I am trying to write a program that will enumerate all possible combinations of assigning 1 to 4 colors to 4 objects. For example, there is one way to assign a single color to four objects, which might be enumerated as: 1111 where each digit indicates an object and values indicate color.
29
3572
by: MP | last post by:
Greets, context: vb6/ado/.mdb/jet 4.0 (no access)/sql beginning learner, first database, planning stages (I think the underlying question here is whether to normalize or not to normalize this one data field - but i'm not sure) :-) Background info:
9
3031
by: kanka | last post by:
Here is my problem, I have a string like $numbers="12345"; i wanna find out all possible (unique) combinations of each subs. e.g. 1 - 2 - 3 - 4 - 5 - 12 - 13 - 14 - 15 - 23 - 24 - ..... - 234 - 245 - .... - 12345 but not 11 - 22 - 21 - 32 - 321.... here is the function that i wrote not returns 13 - 14 - 15 or 24 - 25
1
1451
by: syl | last post by:
Hi I have a huge loto data and i am trying to come up with the total count of all total combination...the manual process to tiring in excel. e.g the possible combinations range from 1 up to 49. so i have to find the combination of numbers e.g 1 2 3 , 1 2 4, 1 2 5, 1 2 6 up to 1 2 49 then move up to 2 3 4 up to 2 3 49 until i will do the same count for 3, 4, 5 6 up to 49. Here is a sample ...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.