感谢很多人的帮助,我得到了以下代码,效果很好。然而,我已经意识到我已经错过了一个重要的信息,因此已经转载(使用更新的代码)澄清。
以下代码从表中获取5个随机记录,并根据第二个表中标识的用户收藏记录获得另一条记录:
CREATE PROCEDURE web.getRandomCharities
(
@tmp_ID bigint --members ID
)
AS
BEGIN
WITH q AS
(
SELECT TOP 5 *
FROM TBL_CHARITIES
WHERE cha_Active = 'TRUE'
AND cha_Key != '1'
ORDER BY NEWID()
)
SELECT *
FROM q
UNION ALL
SELECT TOP 1 *
FROM (
SELECT *
FROM TBL_CHARITIES
WHERE TBL_CHARITIES.cha_Key IN
(
SELECT members_Favourite
FROM TBL_MEMBERS
WHERE members_Id = @tmp_ID
)
EXCEPT
SELECT *
FROM q
) tc
END
但是,我意识到如果它与上面显示的代码中第二个SELECT语句中返回的记录不同,我还需要包含“cha_Key =='1'”的记录。
有意义的HOpe?
感谢!!!
答案 0 :(得分:1)
我不完全确定我理解你,但我相信它会像这样......
没有#1的五个随机记录 一个用户特定记录 如果它不是用户的特定记录,则记录#1。
如果是这样,我相信这样做:
CREATE PROCEDURE web.getRandomCharities ( @tmp_ID bigint --members ID ) AS BEGIN WITH q AS ( SELECT TOP 5 * FROM TBL_CHARITIES WHERE cha_Active = 'TRUE' AND cha_Key != '1' ORDER BY NEWID() ) SELECT * FROM q UNION ALL SELECT TOP 1 * FROM ( SELECT * FROM TBL_CHARITIES WHERE TBL_CHARITIES.cha_Key IN ( SELECT members_Favourite FROM TBL_MEMBERS WHERE members_Id = @tmp_ID ) EXCEPT SELECT * FROM q ) tc UNION ALL SELECT TOP 1 * FROM ( SELECT * FROM TBL_CHARITIES WHERE TBL_CHARITIES.cha_Key NOT IN ( SELECT members_Favourite FROM TBL_MEMBERS WHERE members_Id = @tmp_ID ) AND (TBL_CHARITIES.cha_Key = '1') EXCEPT SELECT * FROM q ) tc END