我前段時間創建了一個凌亂的查詢來獲取產品代碼列表。我正在嘗試清理我的表格和我的代碼。我最近試圖重寫查詢,以便它更易於使用和理解。原始查詢的效果很好,但它需要多個搜索字符串才能執行一次搜索,因爲它使用了UNION,而且還有其他一些問題。我最近修改的查詢更容易理解,只需要一個搜索字符串,但返回的結果不同。基本上新的查詢將記錄留下,我想了解爲什麼以及如何解決它。這裏有兩個查詢(搜索字符串均爲空):重寫mysql查詢返回意想不到的結果,試圖找出原因
原始查詢:
$query = 'SELECT product_code FROM bus_warehouse_lots WHERE status=\'2\''.$search_string_1
.' UNION SELECT product_code FROM bus_po WHERE status=\'0\''.$search_string_2
.' UNION SELECT bus_warehouse_entries.new_product_code AS product_code FROM (bus_warehouse_entries LEFT JOIN bus_warehouse_transfers ON bus_warehouse_entries.picking_ticket_num=bus_warehouse_transfers.pt_number) LEFT JOIN bus_warehouse_lots ON bus_warehouse_entries.ebooks_lot_id=bus_warehouse_lots.id WHERE bus_warehouse_entries.type=\'6\' AND bus_warehouse_transfers.status=\'0\''.$search_string_3
.' UNION SELECT bus_contracts.main_product AS product_code FROM bus_contracts LEFT JOIN bus_warehouse_lots ON bus_contracts.main_product=bus_warehouse_lots.product_code WHERE bus_contracts.status=\'0\''.$search_string_4
.' UNION SELECT prod_id AS product_code FROM bus_products WHERE last_usage > \''.date('Y-m-d', strtotime('-12 months')).'\''.$search_string_5
.' ORDER BY product_code';
新查詢:
$query = 'SELECT bus_products.prod_id FROM bus_products'
.' LEFT JOIN (bus_warehouse_lots, bus_po, bus_warehouse_entries, bus_contracts) ON ('
.'bus_products.prod_id = bus_warehouse_lots.product_code'
.' AND bus_products.prod_id = bus_po.product_code'
.' AND bus_products.prod_id = bus_warehouse_entries.new_product_code'
.' AND bus_products.prod_id = bus_contracts.main_product)'
.' LEFT JOIN bus_warehouse_transfers ON'
.' bus_warehouse_entries.picking_ticket_num = bus_warehouse_transfers.pt_number'
.' WHERE (bus_products.last_usage > \''.date('Y-m-d', strtotime('-12 months')).'\''
.' OR bus_warehouse_lots.status = \'2\''
.' OR bus_po.status = \'0\''
.' OR (bus_warehouse_entries.type = \'6\' AND bus_warehouse_transfers.status = \'0\')'
.' OR bus_contracts.status = \'0\')'
.$search_string_6
.' GROUP BY bus_products.prod_id'
.' ORDER BY bus_products.prod_id';
我們可以得到一個搜索字符串的樣本嗎? – CogitoErgoSum 2010-03-26 16:31:49
爲了測試目的,搜索字符串設置爲空。 – 2010-03-26 21:53:43