I have two table for gallery system :
gallery_cat(
gallery_cat_id PK,
gallery_cat_name
)
gallery(
gallery_id PK,
gallery_cat_id FK,
gallery_name,
gallery_file_name,
gallery_date
)
I need to write a SQL query that return one picture from gallery table for each album, the purpose of this that I need to list the albums with one picture for each.
gallery_name | gallery_cat_name| gallery_file_name
-------------+-----------------+------------------
pic1 | Album1 | pic1.jpg
This should do the trick:
Explanation:
At the end is a sub-select
Here I select all g.id, but because of the
group byclause it will reduce the results to 1 row per grouped by item. I.e. 1 row (chosen more or less at random) perg.gallery_cat_id.Next I do a normal select with a join:
Because I refer to the same table twice in the same query you have to use an alias(*).
I select all names and all catnames and all filenames.
However in the
whereclause I filter these so that only rows from the sub-select are shown.I have to do it this way, because the group by mixes rows into one messed up ow, if I select from that directly I will get values from different rows mixed together, not a good thing.
By first selecting the id’s I want and then matching full rows to those id I prevent this from happening.
*(in this case with this kind of subselect that’s not really 100% true, but trust me on the point that it’s always a good idea to alias your tables)