2011-05-11 73 views
12

繼承人我的代碼:從一個表中選擇,從另算其中id的鏈接

$sql = mysql_query("select c.name, c.address, c.postcode, c.dob, c.mobile, c.email, 
        count(select * from bookings where b.id_customer = c.id) as purchased, count(select * from bookings where b.the_date > $now) as remaining, 
        from customers as c, bookings as b 
        where b.id_customer = c.id 
        order by c.name asc"); 

你可以看到什麼,我試圖做的,但林不知道如何正確地寫這個查詢。

繼承人的錯誤我得到:

警告:mysql_fetch_assoc():提供 參數是不是一個有效的MySQL結果 資源

繼承人我mysql_fetch_assoc:

<?php 

while ($row = mysql_fetch_assoc($sql)) 
{ 
    ?> 

    <tr> 
    <td><?php echo $row['name']; ?></td> 
    <td><?php echo $row['mobile']; ?></td> 
    <td><?php echo $row['email']; ?></td> 
    <td><?php echo $row['purchased']; ?></td> 
    <td><?php echo $row['remaining']; ?></td> 
    </tr> 

    <?php 
} 

?> 
+0

從phpmyadmin或CLI界面執行時,這是否工作? – 2011-05-11 22:07:01

+0

請說明你如何做了你的'mysql_fetch_assoc()'查詢。 – stealthyninja 2011-05-11 22:07:23

+1

我將它添加到原帖... – scarhand 2011-05-11 22:09:13

回答

28

嘗試改變喜歡...

count(select * from bookings where b.id_customer = c.id) 

...到...

(select count(*) from bookings where b.id_customer = c.id) 
17

您的查詢不正確地使用COUNT,它已經覆蓋@Will A's answer

我也想提出一個可能更好的構建替代,我想它,反映了相同的邏輯:

SELECT 
    c.name, 
    c.address, 
    c.postcode, 
    c.dob, 
    c.mobile, 
    c.email, 
    COUNT(*) AS purchased, 
    COUNT(b.the_date > $now OR NULL) AS remaining 
FROM customers AS c 
    INNER JOIN bookings AS b ON b.id_customer = c.id 
GROUP BY c.id 
ORDER BY c.name ASC 

注:通常你預計包括所有非聚集SELECT表達式爲GROUP通過。但是,MySQL支持shortened GROUP BY lists,因此只需指定唯一標識所有正在提取的非聚合數據的關鍵表達式即可。 請避免使用此功能任意。如果未包含在GROUP BY中的列的每個組有多個值,則您無法控制,在拉動該列而沒有彙總時,實際上將返回該值。

+0

這應該是正確的答案。 – jaypabs 2017-03-16 00:50:28

相關問題