問題描述
我有大約 4 個具有完全相同列名的不同表.我想要做的是從所有這些按日期排序的表中選擇前 4 條記錄(因為日期是它們共享的列之一).
I have about 4 different tables with the exact same column names. What I would like to do is select the top 4 records out of all of these tables combined ordered by date (as date is one of the columns that they all share).
我不斷收到錯誤的陳述,無論是語法問題還是含糊不清的記錄等.
I keep getting erroneous statements, whether it be a syntax issue or ambiguous record etc.
基本上我的陳述類似于:
Essentially my statement is similar to:
SELECT TOP 4 date, link, anchor, thumb FROM archive1, archive2, archive3, archive4 ORDER BY date DESC
顯而易見的是,我對所有這些東西都不熟悉.在此先感謝您的幫助.
To state the obvious, I'm new to all this stuff. Thanks in advance for any assistance.
推薦答案
您需要制作 union 所有表,然后對它們進行排序以獲得最后四個:
You need to produce union of all tables and then order them to get last four:
SELECT TOP 4 date, link, anchor, thumb
FROM
(
SELECT date, link, anchor, thumb
FROM archive1
UNION ALL
SELECT date, link, anchor, thumb
FROM archive2
UNION ALL
SELECT date, link, anchor, thumb
FROM archive3
UNION ALL
SELECT date, link, anchor, thumb
FROM archive4
) archive
ORDER BY date DESC
由于您只獲取 4 條記錄,您可以向每個查詢添加 TOP 4 子句以及 ORDER BY 日期 DESC 以加快速度.
As you only take four records you might add TOP 4 clause to each query along with ORDER BY date DESC to speed things up.
這篇關于從多個 SQL Server 表中選擇 TOP 4 記錄.使用 vb.net的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!