MySQL正在重复结果

时间:2016-10-31 18:07:15

标签: php mysql

运行Select并且它为第二个WHERE子句复制了3次结果,有人可以帮我解决。我在网上找不到任何东西,看看能不能自己解决。

Enter something: 
You entered: This is some test string.

当我使用GROUP BY时,它会消失,如果它的工作方式很好但是我担心它不会这样做。

我目前在表格中没有任何重复记录。

Out put看起来像这样:

  • City Grill,2841 E Sprague st - 5
  • Chappy餐厅,13 Main St - 5
  • Chappy餐厅,13 Main St - 5
  • Chappy餐厅,13 Main St - 5
  • Howie's Pizza Bar,552 Ace St - 5
  • Howie's Pizza Bar,552 Ace St - 5
  • Howie's Pizza Bar,552 Ace St - 5
  • House Inc,123 - 5

表:

类别

  • category_id :: 1,2,3
  • 名称:: 酒吧,餐厅,水疗中心

业务

  • business_id :: 1,2,3,4
  • business.name :: City Grill,Chappy's,Howie's; House Inc
  • business.street :: 街道信息
  • category_id :: 1,1,1
  • search_term_1 ::
  • ---通过全部为空
  • search_term_8 :: bar

搜索“bar”

3 个答案:

答案 0 :(得分:2)

似乎错误的where子句,试试这个:

$searchCat = $mysqli->query("
        SELECT 
            business.name, business.street
        FROM 
            business, category
        WHERE 
            category.category_id = business.category_id AND 
        (category.name = '$searchTerm' OR business.search_term_8 = '$searchTerm')
    ")

答案 1 :(得分:1)

如果没有可重现的测试用例,很难说出这里发生了什么,但起初我觉得你没有正确过滤数据。

'或'你的WHERE子句中的术语肯定是罪魁祸首,因为它可以根据数据集向结果集中添加重复的行。它有助于认为OR实际上是两个查询的UNION ALL ...在您的原因中,您的查询将等同于:

SELECT business.name, 
       business.street
  FROM business, category
 WHERE category.category_id = business.category_id 
   AND category.name = '$searchTerm'
 UNION ALL
SELECT business.name, 
       business.street
  FROM business, category
 WHERE business.search_term_8 = '$searchTerm'

请注意,第二个查询中的过滤器仅考虑" business.search_term_8"过滤器,这可能是你不想做的事情(而且它会给出重复的结果)。

请注意,您在类别和业务之间创建了隐式笛卡尔积,因为没有条件将这两个表链接到WHERE子句上。

答案 2 :(得分:0)

我添加了一个联接,这似乎解决了我的问题。

        SELECT 
        business.name, business.street
    FROM 
        business
        LEFT JOIN
        category ON category.category_id = business.category_id
    WHERE 
        category.category_id = business.category_id AND category.name = '$searchTerm'
        OR business.search_term_1 = '$searchTerm'
        OR business.search_term_2 = '$searchTerm'
        OR business.search_term_3 = '$searchTerm'
        OR business.search_term_4 = '$searchTerm'
        OR business.search_term_5 = '$searchTerm'
        OR business.search_term_6 = '$searchTerm'
        OR business.search_term_7 = '$searchTerm'
        OR business.search_term_8 = '$searchTerm'

结果:

  • City Grill,2841 E Sprague st - 5
  • Chappy餐厅,13 Main St - 5
  • Howie's Pizza Bar,552 Ace St - 5
  • House Inc,123 - 5