SQL查询未返回预期结果

时间:2010-10-08 06:08:07

标签: mysql

这是我稍微擦除的SQL查询(只是列/表/数据库名称)。我保持结构与生产相同。这是从我的MySQL日志中获取的查询。

SELECT      master.pk AS pk,
            master.vendor_id AS vendorId,
            master.vendor_text AS vendorName,
            master.device_id AS deviceId,
            master.device_did AS deviceDid,
            master.device_text AS deviceName,
            master.class_id AS classId,
            master.class_text AS className,
            master.oem_id AS oemId,
            master.oem_did AS oemDid,
            master.oem_text AS oemName,
            master.oem_vendor_text AS oemVendor,
            master.comment AS comment,
            master.v1 AS v1,
            master.v2 AS v2,
            master.status AS status,
            dev_mod_join.mod_text AS module
FROM        master
LEFT JOIN   dev_mod_join 
       ON   master.device_did = dev_mod_join.dev_id
WHERE ( 
            master.device_text LIKE CONCAT("%", 'search term', "%")
       OR   master.vendor_text LIKE CONCAT("%", 'search term', "%")
       OR   master.oem_text LIKE CONCAT("%", 'search term', "%")
       OR   master.oem_vendor_text LIKE CONCAT("%", 'search term', "%") 
      )
GROUP BY    master.vendor_text
LIMIT     0, 25

出于某种原因,这只会为每个供应商返回一个结果。这很奇怪。每个供应商可以有多个设备。如果我搜索一个我知道有很多设备的供应商,它仍然只返回该供应商的一个设备(它还返回其他供应商的设备,但其他东西与搜索项匹配,但它只提供一个供应商)。

我缺少的任何东西,我认为它与“OR”有关,但据我所知,情况应该不是这样。

一如既往地感谢帮助。

编辑:天哪,我可能刚想通了。我使用GROUP BY而不是ORDER BY。

哇,看了一会儿,好像花了5分钟,我就明白了。

1 个答案:

答案 0 :(得分:0)

查询似乎在大多数情况下都是合理的,唯一看起来可疑的部分是分组依据。尝试使用不同的select子句而不是group by。

像这样:

SELECT DISTINCT      
            master.pk AS pk,
            master.vendor_id AS vendorId,
            master.vendor_text AS vendorName,
            master.device_id AS deviceId,
            master.device_did AS deviceDid,
            master.device_text AS deviceName,
            master.class_id AS classId,
            master.class_text AS className,
            master.oem_id AS oemId,
            master.oem_did AS oemDid,
            master.oem_text AS oemName,
            master.oem_vendor_text AS oemVendor,
            master.comment AS comment,
            master.v1 AS v1,
            master.v2 AS v2,
            master.status AS status,
            dev_mod_join.mod_text AS module
FROM        master
LEFT JOIN   dev_mod_join 
       ON   master.device_did = dev_mod_join.dev_id
WHERE ( 
            master.device_text LIKE CONCAT("%", 'search term', "%")
       OR   master.vendor_text LIKE CONCAT("%", 'search term', "%")
       OR   master.oem_text LIKE CONCAT("%", 'search term', "%")
       OR   master.oem_vendor_text LIKE CONCAT("%", 'search term', "%") 
      )