MySQL多表查询

时间:2011-03-21 07:53:31

标签: mysql sql join

问候!我在创建引用多个表的查询时遇到了困难。我是SQL的新手并且加入了我。我已经搞砸了Google,在搜索之后我发现Joining tables in SQL让我更接近我想去的地方!我创建的查询不是我想要的。我有两张桌子:

disp_profile
    disp_id*  name      address      zip
    0001      Profile1  SomeAddress1 11111
    0002      Profile2  SomeAddress2 22222
    0003      Profile3  SomeAddress3 33333

zipcode
    zip_code* state     city         county
    11111     CA        City1        County1
    22222     WA        City2        County2
    33333     NV        City3        County3

我试图做的是在zipcode.zip = disp_profile.zip(由变量State过滤)时从zipcode获取City,State,County。理想情况下返回类似:

    dispId    dispName     dispAddress     dispZip    zipState    zipCounty    zipCity  zipCode
    001       Profile1     SomeAddress1    11111      CA          County1      City1    11111
or
    002       Profile2     SomeAddress2    22222      WA          County2      City2    22222


SELECT
    dp.disp_id AS dispId, dp.name AS dispName, dp.address1 AS dispAddress1, dp.zip AS dispZip, zc.state AS zipState, zc.county AS zipCounty, zc.city AS zipCity, zc.zip_code AS zipCode
FROM
    disp_profile dp
INNER JOIN
    zipcodes zc
ON
    dp.zip = zc.zip_code
WHERE
    dp.state = 'CA'

我知道这可能不是解决这个问题的最好方法,但我认为最好分别存储每个项目的冗余信息。 disp_profile中的数据集大约有1000条记录,zip_codes大约是30,000条。使用子查询可以更轻松地完成此操作吗?谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

不,你做得很好。这就是加入的地方,不需要在这里使用子查询。你可以,但它不会表现更好(MySQL查询优化器甚至可能将其转换为内部连接)。

如果您担心速度:在SELECT语句前加上“EXPLAIN”一词,看看MySQL在做什么:

EXPLAIN SELECT
    dp.disp_id AS dispId, dp.name AS dispName, dp.address1 AS dispAddress1, dp.zip AS dispZip, zc.state AS zipState, zc.county AS zipCounty, zc.city AS zipCity, zc.zip_code AS zipCode
FROM
    disp_profile dp
INNER JOIN
    zipcodes zc
ON
    dp.zip = zc.zip_code
WHERE
    dp.state = 'CA'

它会告诉你你的陈述是如何被执行的。如果您希望我们帮助解释,请将输出粘贴到此处:)

答案 1 :(得分:0)

对我来说这看起来没问题,至少乍一看。我更喜欢旧学校的方式:

select dp.disp_id AS dispId,
       dp.name AS dispName,
       dp.address1 AS dispAddress1,
       zc.state AS zipState,
       zc.county AS zipCounty,
       zc.city AS zipCity,
       zc.zip_code AS zipCode
from   disp_profile dp,
       zipcodes zc
where  dp.state = 'CA'
  and  dp.zip = zc.zip_code

但这只是一个风格问题(使用DBMS和一个非常智能的优化器 - MySQL是否与我选择的DBMS相匹配,我无法发表评论(但我对此表示怀疑)。)

已经做出的一次更改(您可能应该这样做)只能获得一个的邮政编码。从dpzc获取字段是多余的,因为由于您的加入,它们是相同的。