我有一张类似的桌子
<div class="home-media-content col-sm-3 px-1 pb-2">
<div class="embed-responsive embed-responsive-16by9">
<?php
$my_query = new WP_Query(
array(
'post_status' => 'publish',
'post_type' => 'page',
)
);
if ( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
the_title(); // Posting just for the test
if ( get_page_template() === 'media-template.php' ) { // This needs to be the file slug rather than template name
do_something();
} else {
do_something_else();
}
}
}
wp_reset_postdata(); // Reset postdata back to normal
?>
</div>
</div>
我需要一种SQL方式来在类型1的行之间选择类型2的行,并传递一行ID
示例:
ID | Type
---------
1 | 1
2 | 2
3 | 2
4 | 2
5 | 1
6 | 2
7 | 2
预先感谢您的帮助
答案 0 :(得分:1)
这是一种方法:
select t.*
from t
where t.id > 5 and
t.type = 2 and
t.id < coalesce( (select min(t2.id)
from t t2
where t2.id > 5 and
t2.type = 1
), 999999999
);
或更优雅:
select t.*
from t
where t.id > 5 and
t.type = 2 and
t.id < all (select t2.id
from t t2
where t2.id > 5 and
t2.type = 1
);
答案 1 :(得分:1)
这是一个可能的选择。
CREATE TABLE SampleData(
ID int,
Type int);
INSERT INTO SampleData
VALUES
(1, 1),
(2, 2),
(3, 2),
(4, 2),
(5, 1),
(6, 2),
(7, 2);
DECLARE @ID int =1;--Parameter
DECLARE @NextID int = (SELECT TOP 1 ID
FROM SampleData
WHERE ID > @ID
AND Type = 1
ORDER BY ID);
SELECT *
FROM SampleData
WHERE Type = 2
AND ID > @ID
AND (ID < @NextID OR @NextID IS NULL);
这将是有关如何创建内联表值函数的示例。
CREATE FUNCTION GetSubset(
@ID int
)
RETURNS TABLE
AS
RETURN
SELECT *
FROM SampleData sd
WHERE sd.Type = 2
AND sd.ID > @ID
AND sd.ID <= ISNULL((SELECT TOP 1 i.ID
FROM SampleData i
WHERE i.ID > @ID
AND i.Type = 1
ORDER BY i.ID), sd.ID);