根据多列组合从表中选择数据

时间:2011-04-25 11:34:24

标签: php mysql

我正在尝试根据heightwidth列的多种组合从表格中选择数据。但是,我正在使用的查询无效。

$sql_wallpaper = "
    SELECT *
    FROM wallpaper
    WHERE categoryid = $catid
    WHERE height = 1080
    OR width = 2560
    OR width = 1366
    OR height = 720
    OR width = 2560
    AND height = 1600
    OR width = 1680
    AND height = 1050
    OR width = 1920
    AND height = 1200
    OR width = 1280
    AND height = 800
    OR width = 1440
    AND height = 900
    ORDER BY wallpaperid DESC
    LIMIT $from,$max_results
";

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

这是因为你的SQL错了:

select * from wallpaper
  where categoryid = $catid
  where height = 1080 OR width = 2560  OR width = 1366
     OR height = 720 OR width = 2560 AND height = 1600
     OR width = 1680 AND height = 1050 OR width = 1920
    AND height = 1200 OR width = 1280 AND height = 800
     OR width = 1440 AND height = 900
  order by wallpaperid desc
  limit $from,$max_results

你有两个WHERE。您应该使用AND代替第二个,也许将所有内容包装成parens。

但也尝试在脚本中使用print mysql_error()。特别是当某些东西不起作用时进行调试。 MySQL会在大多数情况下告诉你查询有什么问题。


非常好。您的重写查询:

select * from wallpaper
  where categoryid = $catid
    AND (
        height = 1080 OR width = 2560  OR width = 1366
     OR height = 720 OR width = 2560 AND height = 1600
     OR width = 1680 AND height = 1050 OR width = 1920
    AND height = 1200 OR width = 1280 AND height = 800
     OR width = 1440 AND height = 900
        )
  order by wallpaperid desc
  limit $from,$max_results

但为了简单起见,你可能应该使用的是:

SELECT * FROM wallpaper
  WHERE categoryid = $catid
    AND width IN (1440, 2560, 1366, 1680, 1920, 1280)
    AND height IN (1200, 800, 900, 1080, 720, 1600, 1050)
  ORDER BY wallpaperid DESC
  LIMIT $from,$max_results