帮助mysql加入

时间:2011-08-20 17:25:39

标签: mysql sql join

我可以获得MySQL JOIN的帮助吗?

基本上我有4个表,交易员,街道帐户(与交易者相关联),recommendation_brokerages和推荐。我需要从交易者表中获取所有交易者姓名和电子邮件地址,其中交易者streetaccount.brokerage_id存在于recommendation_brokerages表和推荐表中。

这是我桌子的基本结构。

tbl_traders
--------------------------------------
trader_id | trader_name | email
--------------------------------------

tbl_streetaccounts
--------------------------------------
trader_id | brokerage_id
--------------------------------------

tbl_recommendation_brokerages
--------------------------------------
recommendation_id | brokerage_id
--------------------------------------

tbl_recommendations
--------------------------------------
recommendation_id | published
--------------------------------------

2 个答案:

答案 0 :(得分:2)

select t.* from tbl_traders t
inner join tbl_streetaccounts s on t.trader_id = s.trader_id
inner join tbl_recommendation_brokerages rb on s.brokerage_id = rb.brokerage_id
inner join tbl_recommendations r on t.recommendation_id = r.recommendation_id

注意,通常认为具有描述类型的前缀“无用”。这种80年代的做法经常受到批评。

请参阅Joel http://www.joelonsoftware.com/articles/Wrong.html

在这篇文章中的“我是匈牙利”一节

答案 1 :(得分:0)

假设tbl_recommendation_brokerages.recommendation_idtbl_recommendations.recommendation_id的外键,我们无需加入tbl_recommendations

SELECT
    t.trader_name, 
    t.email
FROM
    tbl_traders t
WHERE
    EXISTS (
        SELECT
            *
        FROM
            tbl_streetaccounts acct,
            tbl_recommendation_brokerages rec
        WHERE
            acct.brokerage_id = rec.brokerage_id
            AND acct.trader_id = t.trader_id
        )