2011-04-11 272 views
0

我使用的是C#控制檯應用程序,以獲得從MySQL數據庫中的一些數據,我有一些問題得到的查詢權幫助MySQL查詢

因爲它現在是:

SELECT * FROM Customer 
WHERE EXISTS (SELECT * FROM Customer_x_Billing c WHERE Customer.`customer id` = c.customer_id) 
AND 2011 -04 -03 < (SELECT last_changed FROM Customer_x_Billing c WHERE Customer.`customer id` = c.customer_id) 
ORDER BY Customer.`customer id` 

我怎麼能改進這一個? 我想要獲得所有在Customer和Customer_x_Billing表中都有其ID並且Customer_x_Billing中的last_changed日期大於參數(本例中爲2011-04-03)的所有客戶。如果我將日期設置爲2012-04-03,則不應該返回任何行,但會返回與第一個條件相匹配的所有記錄(兩者均存在)。

在此先感謝。

+0

沒有太多的分析你的查詢,查詢中最明顯的問題就是你指定日期參數的方式。你得到的東西被解釋爲一個算術表達式,'2011-04-03',它被相應地評估,然後當與子查詢的結果進行比較時隱式轉換爲日期/時間值。爲了將參數解釋爲日期,您需要將其作爲單引號括起來,就像大多數答案所示。 – 2011-04-11 07:28:51

回答

0

SELECT c.* FROM Customer c INNER JOIN Customer_x_Billing cb ON cb.customer_id = c.id WHERE DATE(cb.last_changed) > '2011-04-03' ORDER BY c.id;

0

如果我讀了你的問題的權利我相信你可以用INNER JOIN實現這個...

SELECT * 
FROM Customer c 
INNER JOIN Customer_x_Billing b 
    ON c.customer_id = b.customer_id 
WHERE last_changed_date > '2011-04-03' 
1

嘗試下面一個

SELECT * FROM Customer 
INNER JOIN 
Customer_x_Billing ON Customer.`customer id` = Customer.customer_id 
WHERE last_changed > 2011 -04 -03 
ORDER BY Customer.`customer id` 

問題與您查詢您正在掃描Customer_x_Billing表兩次不需要的內容,最好去一個內部聯接,它將穩定您首先調用存在的一個和第二個sati通過編寫where子句來實現。

0
SELECT Customer.* FROM Customer c INNER JOIN Customer_x_Billing b 
ON c.`customer id`=b.`customer id` 
WHERE last_changed>'2011-04-03' 
ORDER BY c.`customer id` 

不管怎樣提防在查詢日期...

0

更多或更少的這樣。

using (SqlConnection con = new SqlConnection(connectionString)) 
{ 
    using (SqlCommand cmd = new SqlCommand()) 
    { 
    cmd.Connection = con; 
    cmd.CommandText 
     = "SELECT * FROM Custromer c JOIN Customer_x_Billing cb ON c.'customer id' = cd.'customer id' Where last_change < @lastChangeDate"; 
    cmd.Parameters.AddWithValue("@lastChangeDate", new DateTime(2011,04,03)); 
    using (SqlDataReader drd = cmd.ExecuteReader()) 
    { 
     while (drd.Read()) 
     { 
     // Read from data reader 
     } 
    } 
    } 
} 

爲您的應用程序的緣故,你應該熟悉一些數據庫教程,並嘗試瞭解關係數據庫的概念。