SQL连接 - 希望在一个表中搜索关键字,另外两个表

时间:2014-01-31 19:37:11

标签: mysql sql

我不熟悉SQL连接。基本上我试图能够在通过某个stateID进行过滤时搜索公司名称以获取关键字(比方说7)。这是我的设置:

公司表 - companyID,company_name

表table-stateID,state

company_states - companyID,stateID

到目前为止,我能够想出的就是:

select * from company where `exchange-name` like 
'%associates%' inner join company_states on ....

例如,我需要company_states的stateID匹配7以及匹配其中一个名称包含“associates”的公司。任何帮助将非常感激。

2 个答案:

答案 0 :(得分:1)

一种解决方案是将所有三个现有表连接在一起,并根据需要编写where子句。建议:

select
    c.company_name

from
    company c join company_states cs on c.companyID = cs.companyID
    join states s on cs.stateID = s.stateID

where
    c.company_name like '%associates%'
and
    s.stateID = 7

答案 1 :(得分:0)

select c.* from company AS c LEFT JOIN company_states AS st ON c.companyID = st.companyID where `exchange-name` like '%associates%' AND st.stateID = 7

说明:

SELECT c.* /* Only select columns from company table, not the joined linker table */
FROM company AS c /* Define a table alias, because im lazy */
LEFT JOIN company_states AS st /* Join the linker table in and alias again */
ON c.companyID = st.companyID /* We tell MySQL what column in company table is to match the column in linker table */
WHERE `exchange-name` like '%associates%' /* filter the companies by name */
AND st.stateID = 7 /* filter out companies who dont have a linked state of ID 7 */

我倾向于使用LEFT JOIN作为我的默认连接类型,因为我构建数据的方式并且我很少需要使用不同的连接类型。

但是你可以在这里找到一个简单易懂的联接指南:http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html