1

此查询有效.. 一次查询 50 个 mysql 数据库并返回最近的 10 个结果,但是.. 有没有办法不查询每个状态的整个数据库(我的示例中仅列出 4 个状态),只需获取顶部10(按timeStamp desc)并使此查询更有效率?

$query = "    
SELECT imgURLThumb, timeStamp, title2, state, postId, title
FROM (
  SELECT imgURLThumb,timeStamp, title2, state, postId, title FROM db_washington.md_postings UNION ALL 
  SELECT imgURLThumb,timeStamp, title2, state, postId, title FROM db_westvirginia.md_postings UNION ALL 
  SELECT imgURLThumb,timeStamp, title2, state, postId, title FROM db_wisconsin.md_postings UNION ALL 
  SELECT imgURLThumb,timeStamp, title2, state, postId, title FROM db_wyoming.md_postings 

) allposts where imgURLThumb <> 'images/nopicture.png' order by timeStamp DESC LIMIT 0 , 10";
4

1 回答 1

1

您应该重新设计您的数据库,以便所有的帖子都在一个数据库中,以使这个查询更容易编写。每个州都有一个数据库看起来是个糟糕的设计。相反,您应该有一个md_postings用于所有过帐的表,其中一个字段是State

如果这是不可能的,那么我认为你有一个权衡:

  • 简洁易读的 SQL 或
  • 很棒的表演。

如果你想要更好的性能试试这个:

SELECT imgURLThumb, timeStamp, title2, state, postId, title
FROM (
    (SELECT imgURLThumb,timeStamp, title2, state, postId, title
    FROM db_washington.md_postings
    WHERE imgURLThumb <> 'images/nopicture.png'
    ORDER BY timeStamp DESC
    LIMIT 10)

    UNION ALL

    (SELECT imgURLThumb,timeStamp, title2, state, postId, title
    FROM db_westvirginia.md_postings
    WHERE imgURLThumb <> 'images/nopicture.png'
    ORDER BY timeStamp DESC
    LIMIT 10)

    UNION ALL

    (SELECT imgURLThumb,timeStamp, title2, state, postId, title
    FROM db_wisconsin.md_postings
    WHERE imgURLThumb <> 'images/nopicture.png'
    ORDER BY timeStamp DESC
    LIMIT 10)

    UNION ALL

    (SELECT imgURLThumb,timeStamp, title2, state, postId, title
    FROM db_wyoming.md_postings
    WHERE imgURLThumb <> 'images/nopicture.png'
    ORDER BY timeStamp DESC
    LIMIT 10)
) AS allposts
WHERE imgURLThumb <> 'images/nopicture.png'
ORDER BY timeStamp DESC LIMIT 10
于 2012-05-24T06:56:37.557 回答