如果第二个匹配,mysql从两个表中选择信息

时间:2015-08-31 12:50:16

标签: mysql sql

我有两张桌子。不是每一行都与table2相连,但如果它们是id,则供应商是相同的。我想从table1中选择查询LIKE或匹配的所有记录,但它只会选择供应商是否也在table2中。有什么想法吗?

table1
id          | 1
supplier    | 1

额外信息表:

table2
id        | 1
supplier  | 1
extrainfo | "Best information"

查询

SELECT
    table1.*,table2.*
FROM
    mytable_normalinfo as table1,
    mytable_extrainfo as table2
WHERE 
  MATCH(table1.fulltextcollum)
  AGAINST ('+test*' IN BOOLEAN MODE)
AND
     table1.supplier =  table2.supplier 
AND
     table1.id = table2.id
LIMIT 10;

1 个答案:

答案 0 :(得分:4)

我想你只想要left join

SELECT table1.*, table2.*
FROM mytable_normalinfo as table1 LEFT JOIN
     mytable_extrainfo as table2
     ON table1.supplier =  table2.supplier AND
        table1.id = table2.id
WHERE MATCH(table1.fulltextcollum) AGAINST ('+test*' IN BOOLEAN MODE)
LIMIT 10;

两个注释:

  • 学习使用正确的JOIN语法。简单规则:从不FROM子句中使用逗号。
  • 使用LIMIT时,通常也会使用ORDER BY