我有一个MySQL表,我喜欢在其中执行查询。我的桌子看起来如下:
日期活动金额 ----------------------------- 第1天喝0 第1天吃1 第1天呼吸1 第2天喝0 第2天吃0 第2天呼吸0 第3天喝1 第3天呼吸0 第四天吃1 ETC ETC ETC
我想做的就是看看何时吃1,而这是事实,我想展示那些日子的所有活动
//我现在正在做的是:$ activityArray = array();$ result = mysql_query(" select * where atction ='eat'and量='1'");$ row = mysql_fetch_assoc($ result);//这将返回所有行,其中活动=饮食和金额= 1做{ //为每个结果行执行一个新查询;查找第一个查询中的'date'= $ row [date],并显示当天完成的所有活动(活动= 1) $ result2 = mysql_query(" select * wert where date ='"。$ row [date]。''"); $ row2 = mysql_fetch_assoc($ result2); 做{ array_push($ activationarray,$ row2 ['active']); } while($ row2 = mysql_fetch_assoc($ result2));} while($ row = mysql_fetch_assoc($ result));print_r($ cistivearray);
由于每天有数千天和数十种活动,因此这似乎不是我最有效的方法。有什么方法可以通过一个查询更有效地做到这一点?(因此:检查食用= 1的日子的所有活动)。希望任何人都可以我出去!
使用自加入:
SELECT t1.*
FROM table AS t1
JOIN table AS t2 ON t1.date = t2.date
WHERE t2.activity = 'eat' AND t2.amount = 1
我的建议,尤其是在加入大小限制的情况下:
select *
from table as t1
where exists (
select 1
from table as t2
where t2.date = t1.date
and t2.activity = 'eat'
and t2.amount = 1
)