2

我有一个名为is_thumbnail默认值的列no。我根据以下选择一行is_thumbnail = 'yes'

    $query = $conn->prepare("SELECT * FROM project_data 
                            WHERE project_id = :projectId 
                            AND is_thumbnail = 'yes' 
                            LIMIT 1");

有可能没有行的值为yes。在这种情况下,我想选择具有相同projectId值的第一行,而不管is_thumbnail

现在我知道我可以看到查询返回的内容,然后运行另一个查询。我想知道是否可以在单个查询中执行此操作,或者是否可以通过某种方式利用 PDO?我刚开始使用 PDO。谢谢!

示例数据:

id  project_id image                              is_thumbnail 
20  2          50f5c7b5b8566_20120803_185833.jpg  no
19  2          50f5c7b2767d1_4link 048.jpg        no
18  2          50f5c7af2fb22_4link 047.jpg        no
4

2 回答 2

3
$query = $conn->prepare("SELECT * FROM project_data 
                            WHERE project_id = :projectId 
                            ORDER BY is_thumbnail ASC LIMIT 1");
于 2013-01-15T23:37:11.010 回答
1

鉴于问题中描述的模式显示给定的多行,如果有例如具有许多相关行的单个项目,则project_id仅使用解决方案可能不会产生良好的性能。ORDER BY is_thumbnail ...对行进行排序的成本可能相当高,并且无法使用索引。可能需要的替代解决方案是:

SELECT * FROM (
  SELECT *
  FROM project_data 
  WHERE project_id = :projectId AND is_thumbnail = "yes"
  ORDER BY id DESC
  LIMIT 1

  UNION

  SELECT *
  FROM project_data 
  WHERE project_id = :projectId AND is_thumbnail = "no"
  ORDER BY id DESC
  LIMIT 1
) AS t 
ORDER BY t.is_thumbnail = "yes" DESC
LIMIT 1

虽然这个解决方案理解起来有点复杂,但它能够使用复合索引(project_id, is_thumbnail, id)来快速找到与请求条件完全匹配的行。如果两者都找到,则外部选择可确保是/否行的稳定排序。

Note that you could also just issue two queries, and probably get similar or better performance. In order to use the above UNION and sub-select, MySQL will require temporary tables, which aren't great in busy environments.

于 2013-01-16T00:04:29.587 回答