views:

27

answers:

1
usertable
----
id, username

grouptable
----
id, groupname

group_user
--------
uid, gid

books
----
id, groupname

Input parameters: groupname, username
output: list of books

Is it possible to use 1 sql statement to get list of books when username is inside groupname

Question 2: any good book to recommand to master complex sql statement..

+1  A: 

Hi,

This query gives list of books by user parametar

SELECT b.id,
FROM usertable u
     INNER JOIN group_user gu ON gu.uid = u.id
     INNER JOIN grouptable g ON g.id= gu.gid
     INNER JOIN books b ON b.groupname = g.groupname 
WHERE u.username = @user_name

Also i think if you have the group name you can use

SELECT b.id,
FROM grouptable g 
     INNER JOIN books b ON b.groupname = g.groupname 
WHERE g.groupname = @group_name

Bus having select on both parameters i think is not very good think. This query will get list of books for user group name

SELECT b.id,
    FROM usertable u
         INNER JOIN group_user gu ON gu.uid = u.id
         INNER JOIN grouptable g ON g.id= gu.gid
              AND g.group_name = @group_name
         INNER JOIN books b ON b.groupname = g.groupname 
    WHERE u.username = @user_name
IordanTanev
just to confirm, u are using inner join. but same user can have multiple different books. inner join means 1 left table-1 right table join(full join) in this case unique user will be listed which is incorrect..? sorry if i'm wrong and please explain
cometta
using the Where clause i leave only one row in the usertable the user with username the same as the parameter value. Using inner join i get as many rows as user is part of. So if user is in 5 groups i get five row. Then i filter these groups by parameter @group_name. The i get book list for this group. If it is still not clear how it works just replace "b.id" with "*" and remove all the inner join and the where clause and start adding them one by one to see the effect
IordanTanev