2016-12-14 126 views
0

我有一個MySQL表,我喜歡在其上執行查詢。我的表看起來如下:PHP「數組查詢」/多個查詢

 
    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

somethign像'SELECT * FROM表WHERE天=(選擇從那裏活動日='eat'AND amount ='1')' – 2016-12-14 20:31:04

+1

@dagon這應該是'WHERE一天IN ...' – Barmar

+0

ahy,yup,它只是一個快速的儘管 – 2016-12-14 20:34:18

回答

1

使用自聯接:

SELECT t1.* 
FROM table AS t1 
JOIN table AS t2 ON t1.date = t2.date 
WHERE t2.activity = 'eat' AND t2.amount = 1 
+0

當我嘗試時,我收到以下消息: SELECT將檢查多個MAX_JOIN_SIZE行;檢查你的WHERE並使用SET SQL_BIG_SELECTS = 1或SET MAX_JOIN_SIZE =#如果SELECT可行 – mh3982

+0

嘗試在'date'列中添加一個索引。 – Barmar

+0

我該怎麼做? de查詢如何變得像? – mh3982

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 
    )