我有一个mysql表,我喜欢在上面执行查询。我的表格如下:
date activity amount -------- ------ -------- day 1 drink 0 day 1 eat 1 day 1 breath 1 day 2 drink 0 day 2 eat 0 day 2 breath 0 day 3 drink 1 day 3 breath 0 day 4 eat 1 etc etc etc
我想做的是看看吃什么时间是1,而事实上,我希望显示那些日子里的所有活动
//What I was doing right now is: $activityarray = array(); $result = mysql_query("SELECT * FROM table WHERE activity='eat' AND amount='1'"); $row = mysql_fetch_assoc($result); //this returns all rows where activity=eat and amount=1 do{ //perform for each result row a new query; look for the 'date'=$row[date] from the first query and show all activities that have been done that day (activity=1) $result2 = mysql_query("SELECT * FROM table WHERE date='".$row[date]."'"); $row2 = mysql_fetch_assoc($result2); do{ array_push($activityarray,$row2['activity']); }while($row2 = mysql_fetch_assoc($result2)); }while($row = mysql_fetch_assoc($result)); print_r($activityarray);
由于每天有数千天和数十项活动,这对我来说似乎不是最有效的方法。有一种方法可以通过一个查询提高效率吗? (所以:检查所吃的日子的所有活动= 1)。 希望有人能帮帮我!
答案 0 :(得分:1)
使用自我加入:
SELECT t1.*
FROM table AS t1
JOIN table AS t2 ON t1.date = t2.date
WHERE t2.activity = 'eat' AND t2.amount = 1
答案 1 :(得分:0)
我的建议,特别是如果您有加入尺寸限制:
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
)