[英]mysql value check with next row value
我有名為cm的mysql表
CREATE TABLE `cm` (
`id` int(10) NOT NULL,
`chit_no` varchar(30) DEFAULT NULL,
`pjt_no` varchar(20) DEFAULT NULL,
`design` varchar(25) DEFAULT NULL,
`item` varchar(25) DEFAULT NULL,
`process` varchar(10) DEFAULT NULL,
`times` int(1) DEFAULT NULL,
`current_position` int(1) DEFAULT NULL,
`current_stage` int(1) DEFAULT NULL,
`qty` int(10) DEFAULT NULL,
`dmg` int(2) DEFAULT NULL,
`bbelt` varchar(10) DEFAULT NULL,
`fdate` date DEFAULT NULL,
`remarks` varchar(500) DEFAULT NULL,
`shift` int(1) DEFAULT NULL,
`date` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
表格視圖
該表包含10萬條記錄。 我只想獲取具有Process = Firing和last_record = 1 AND qty> 0的行, 以及下一條記錄qty = 0的特定日期范圍的行
我嘗試過此代碼,但沒有輸出。
$sql =mysql_query("SELECT *
FROM cm
WHERE ( process='Firing'
AND qty>0
AND last_record='1'
)
AND 1>(SELECT qty
FROM cm
WHERE id=id+1)
AND fdate BETWEEN '$from' AND '$to'
ORDER BY cm.id,design, item,chit_no")
or die ("err1");
首先,需要特別注意的是,除非您基於對存儲數據的了解進行定義,否則i SQL Server永遠不會存在“下一條記錄”。
MySQL傾向於按照未添加記錄的順序將它們添加到服務器中,但是您從未真正知道。
因此,首先,我們必須根據圖像中的數據定義“下一條記錄”,我想您想要的是基於id的下一條記錄。 如果您知道ID每條記錄增加一個,並且記錄從不刪除,那么我們可以很容易地找到“下一個”記錄。
select
c.*
from
cm c
where
c.process='Firing'
and
c.last_record=1
and
c.qty>0 /*easy part done*/
and
exists (select id from cm c2 where c2.id=c1.id+1 and c2.qty=0)
如果您可以基於id序列中沒有空格的事實進行查詢,這將使您想得到。
我真的不知道這是什么類型的應用程序,但是由於您要基於“下一個”行比較和選擇行,因此我認為記錄按某種方式分組(設計ID?),而“下一個記錄”可能不會僅基於ID,但也應考慮設計。
如果您的ID序列中有間隔,或者需要對記錄進行分組以定義“下一個”,那么查詢會慢很多,但是您可以執行以下操作:
select
c.*
from
cm c
where
c.process='Firing'
and
c.last_record=1
and
c.qty>0 /*easy part done*/
and
exists (select id from cm c2 where c2.Id=(select min(id) from cm c3 where c3.id>c.id and c3.design=c1.design) and c2.qty=0)
如果可能,還請重新評估您的數據模型/ bis邏輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.