2013-08-26 26 views
0

我搜索了類似的問題,但我得到的是「CREATE TABLE IF NOT EXISTS」。Paris/Idiorm:檢查數據庫是否爲空?

這不是我想要的!我只想檢查5個需要的表是否存在,創建它們是完全不同的事情。

含義我只想要「IF NOT EXISTS」部分,沒有「CREATE TABLE」。無論如何與Idiorm做到這一點? P/S:如果可能,請寫出整個代碼行(例如ORM :: raw_execute('query')或其他)。我幾乎沒有任何經驗的數據庫查詢:()

+0

請點擊此鏈接:http://stackoverflow.com/questions/8829102/mysql-check-if-table-exists-without-using-select-from – user1502952

回答

1

花費數小時到在此之後,問題來:「我怎麼運行執行SQL在paris/idiorm中查詢並獲取查詢結果?「

Ididorm的raw_execute()不返回查詢結果,而是返回true,如果查詢成功執行,否則返回false。

最後,我解決了這個問題:

ORM :: for_table( '') - > raw_query( 「SQL查詢來檢查表的存在」) - > find_one();

我不給一個表名作爲for_table()的參數,而是給它一個空字符串,然後調用一個raw_query(),這相當於直接調用一個原始查詢。它在我的情況下工作。我還必須重置Idiorm的數據庫連接,並清除緩存以便在不同dbs之間切換時使用它。

+0

我的版本做這個 $ q = ORM :: for_table ('') - > raw_query(「show tables like'table_to_be_tested'」) - > find_one(); if($ q){ echo「table exists!\ n」; } else { echo「table does not exist \ n」; } – cwhsu

0

MySQL的工作,你可以查詢information_schema.tables視圖

SELECT n.table_name, 
     case when x.table_name is null 
      then 'Does not exist' 
      else 'Exists' 
     end as chk 
FROM (
    select 'mytable' as table_name union all 
    select 'table1' union all 
    select 'tbl1' union all 
    select 'another_table' union all 
    select 'fifth_table' 
) n 
LEFT JOIN information_schema.tables x 
ON (x.table_schema = 'test' AND x.table_name = n.table_name); 



+ --------------- + -------------- + 
| table_name  | chk   | 
+ --------------- + -------------- + 
| mytable   | Exists   | 
| tbl1   | Exists   | 
| table1   | Does not exist | 
| another_table | Does not exist | 
| fifth_table  | Does not exist | 
+ --------------- + -------------- +