如何正确使用此IN
OR
选择语句?(除了where bdt.active='yes'
之外,一切实际上都可以工作)
SELECT bdt.*, specials.*, stars.*
FROM bdt INNER JOIN specials ON bdt.id = specials.id
INNER JOIN stars ON specials.id=stars.id
WHERE bdt.active='yes'
AND bdt.business_type IN ('entertainment')
OR bdt.business_subtype IN ('entertainment')
OR bdt.subtype2 IN ('entertainment')
OR specials.type IN ('entertainment')
您只需要在第二个AND
条件中使用括号()
,如下所示:
SELECT bdt.*, specials.*, stars.*
FROM bdt INNER JOIN specials ON bdt.id = specials.id
INNER JOIN stars ON specials.id=stars.id
WHERE bdt.active='yes'
AND (bdt.business_type IN ('entertainment')
OR bdt.business_subtype IN ('entertainment')
OR bdt.subtype2 IN ('entertainment')
OR specials.type IN ('entertainment'))
2 个关于风格的注释。
- 使用
IN
当您有多个选择时,请使用=
进行单个直接匹配。 -
SELECT bdt.*, specials.*, stars.*
形式真的很糟糕。 从联接中可以明显看出每个表都有一个id
字段。 您需要仅列出所需的列,并以不同的方式为同名列设置别名。
我还将在下面展示如何使用 IN
正确重写 OR
子句。
SELECT bdt.*, specials.*, stars.*
FROM bdt INNER JOIN specials ON bdt.id = specials.id
INNER JOIN stars ON specials.id=stars.id
WHERE bdt.active='yes'
AND 'entertainment' IN (bdt.business_type, bdt.business_subtype,
bdt.subtype2, specials.type)