doumi4676 2014-12-14 23:50
浏览 41
已采纳

mySQL结合表查询数据

Just doing some mySQL problems and have figured out all but the very last one (of course).

I have two tables.

The Question asked is "Write a query to return a list of all authors who live in the same city as any publisher."

Apologies as I'm not allowed to post images. But It's easy to figure out the headings to it's value nevertheless. I've added commas into the first few to separate them so you know the general workings.

Publishers table

PUB_ID PUB_NAME CITY STATE COUNTRY
0736 New Moon, Palo Alto, CA, USA
0877 Binnet & Hardley, Washington, DC, USA
1389 Algodata, Berkeley, CA, USA
1622 Five Lakes, Chicago, IL, USA
1756 Ramona Publishers Oakland CA USA
9901 GGG&G Munich NULL NULL
9952 Scootney Books New York NY USA
9999 Lucerne Publishing Paris NULL France

Authors table

AU_ID LNAME FNAME PHONE ADDRESS CITY STATE CONTRACT
172 White Johnson, 496-7223, 10932 Bigge Rd Menlo Park, CA 1
213 Green Marjorie, 986-7020, 309 63rd St. Oakland, CA 2
238 Carson Cheryl, 548-7723, 589 Darwin Ln, Berkeley, CA 1
267 O‟Leary Michael 286-2428 22 Cleveland Av San Jose CA 1
274 Straight Dean 834-2919 5420 College Av Oakland CA 2

I understand I have to use an Inner Join statement but how to do that AND match up the authors that live in the same city as a publisher is what is confusing me.

  • 写回答

1条回答 默认 最新

  • duanqiang7631 2014-12-14 23:56
    关注
    SELECT a.*
    FROM Authors AS a
    JOIN (SELECT DISTINCT city, state
          FROM Publishers) AS p
    ON a.city = p.city AND a.state = p.state
    

    DISTINCT prevents it from producing multiple results for an author if there's more than one publisher in their city.

    You can also do it with a correlated subquery:

    SELECT *
    FROM Authors AS a
    WHERE EXISTS (SELECT *
                  FROM Publishers AS p
                  WHERE p.city = a.city AND p.state = a.state)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改