简体   繁体   中英

I need query to pair every item in a table, with every other item, but only once

I have a set of Locations in a table like so:

╔═══════════╗
║ Locations ║
╠═══════════╣
║ A         ║
║ B         ║
║ C         ║
╚═══════════╝

And I want to match every location in the table against every other location in the table, where the locations are not the same, currently I use this query. SELECT a.PostCode AS X, b.PostCode AS Y FROM locations a JOIN locations b WHERE a.Location_ID != b.Location_ID; And this returns a result set like this.

╔═══╦═══╗
║ X ║ Y ║
╠═══╬═══╣
║ B ║ A ║
║ C ║ A ║
║ A ║ B ║
║ C ║ B ║
║ A ║ C ║
║ B ║ C ║
╚═══╩═══╝

Which is not really what I need, as for my purposes the pairs (B, A) and (A, B) are the same, I would like to know if there is a way to use an SQL query (MYSQL) to produce a result set like so:

╔═══╦═══╗
║ X ║ Y ║
╠═══╬═══╣
║ B ║ A ║
║ C ║ A ║
║ C ║ B ║
╚═══╩═══╝

Simply change your where condition to > :

SELECT a.PostCode AS X,
       b.PostCode AS Y 
FROM locations a CROSS JOIN 
     locations b 
WHERE a.Location_ID > b.Location_ID;

When you don't have an ON clause, you should use CROSS JOIN . MySQL is the only database that allows other JOIN s not to have an ON clause.

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