开发者

Need to use criteria from multiple tables to acquire data from multiple tables

I'm having a bit of a hiccup regarding a particular SQL query. I need to join data from two tables, while also limiting the data (but not necessarily grabbing it) by means of a third table. The tables are as follows:

    MEMBERS(member_id,first_name,last_name)
    MEMBERS_GROUPS(member_id,group_id)
    CHARGES(charge_id,member_id,charge_amount,status)

I need to find all charges for all members of a specific group but I also want to grab the first and last name from the MEMBERS table. The query I've come up with thus far is:

select c.*, m.first_name, m.last_name 
FROM charges c 
LEFT JOIN member m 
    ON c.member_id=m.member_id 
INNER JOIN members_groups m开发者_如何学运维g 
    ON mg.group_id=1

i've also tried:

SELECT c.*, m.first_name, m.last_name 
FROM charges c, members_groups mg, member m 
WHERE c.member_id=mg.member_id 
   AND mg.group_id = 1 
   AND c.status='Valid' 
   AND c.member_id = m.member_id

…but neither returns the data I need. I'm sure I'm overthinking this, but I can't for the life of me get the correct values. I keep getting what appears to be the Cartesian product -- regardless, it's clearly returning too many rows and bad data.


Perhaps what you need is to also restrict the INNER JOIN on members_groups to those rows with mg.member_id = m.member_id:

SELECT c.*, m.first_name, m.last_name 
FROM charges c 
LEFT JOIN member m 
    ON c.member_id=m.member_id 
INNER JOIN members_groups mg 
    ON mg.group_id=1
    AND mg.member_id = m.member_id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜