Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Need help with Subqueries in FROM clause

$
0
0

Hi, I'm novice with SQL and this is my first post on the forum.
I hope to learn quickly to help those who need my time.
My question relates to the following tables:

COMMENTS
id_comment|comment_product|comment_date|product_id|user_id
1         |Lorem 1        |2013/06/12  |1         |1
2         |Lorem 2        |2013/06/15  |2         |2
3         |Lorem 3        |2013/06/16  |1         |1
4         |Lorem 4        |2013/06/16  |2         |2
5         |Lorem 5        |2013/06/16  |2         |3
6         |Lorem 6        |2013/06/17  |1         |4
7         |Lorem 7        |2013/06/18  |1         |1

productS
id_product|product_name
1         |product1
2         |product2
3         |product3


PHOTOS
id_photo|photo_url|photo_date|product_id
1       |url1.com |2012/08/12|1 
2       |url1.com |2012/09/16|3
3       |url1.com |2012/08/17|1
4       |url1.com |2012/12/18|3
5       |url1.com |2013/05/21|1
6       |url1.com |2013/06/16|1



USERS
id_user|user_name|user_avatar_url
1      |user1    |http://url1.com
2      |user2    |http://url2.com
3      |user3    |http://url3.com
4      |user4    |http://url4.com
5      |user5    |http://url5.com


EXPECTED RESULTS
id_product|product_name|total_comments|id_comment|comment_product|comment_date|id_user|user_name|user_avatar_url|id_photo|photo_url|photo_date
1         |product1    |4             |7         |Lorem 7        |2013/06/18  |1      |user1    |http://url1.com|6       |url6.com |2013/06/16
2         |product2    |3             |7         |Lorem 4        |2013/06/16  |2      |user2    |http://url2.com|NULL    |NULL     |NULL
3         |product3    |0             |NULL      |NULL           |NULL        |NULL   |NULL     |NULL           |4       |url4.com |2012/12/18
        

The result I want to achieve is shown in the last table.

For each product I would like to extrapolate the number of comments received, the final comment and the data of the user who wrote it (if any), and the last picture that was inserted (if it exists).

Can anyone show me the best way (and most appropriate), in terms of performance, to solve this request?


Viewing all articles
Browse latest Browse all 23857

Trending Articles