在我的php代码中,我想从这样的表中删除列:
function delete_table_column_db( $table_name, $column_attrs ){
global $wpdb;
$res = $wpdb->query( "ALTER TABLE " . $table_name . " DROP " . $column_attrs['name'] );
if( $res === false ){
error_log( sprintf("The column %s could not be deleted for the table %s", $column_attrs['name'], $table_name ) );
}
}
但是如果表只有一列,则此函数会出错:
ERROR 1090 (42000): You can't delete all columns with ALTER TABLE; use DROP TABLE instead
因此,我想DROP TABLE
是表的最后一列。
为此,我需要检查它是否是最后一个表格列。
有办法吗?
答案 0 :(得分:1)
要计算表中的列数,我们将需要使用INFORMATION_SCHEMA.COLUMNS
。仅当用户有权访问INFORMATION_SCHEMA
表时,以下解决方案才有效。
您可以按以下方式获取表中的总列数:
SELECT COUNT(*) AS no_of_columns
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '$your_table_name' AND
TABLE_SCHEMA = '$your_database_name'
因此,您可以首先使用此查询,获取列数。如果大于1,则可以继续进行ALTER TABLE .. DROP COLUMN
查询。
information_schema.columns
表中的一些值得注意的列是:
TABLE_SCHEMA
-表所指向的架构(数据库)的名称 包含列所属。
TABLE_NAME
-包含该列的表的名称。
COLUMN_NAME
-列的名称。
答案 1 :(得分:0)
基于@Madhur Bhaiya答案的完整代码:
class Resume < ActiveRecord::Base
has_many :user_skills, :dependent => :destroy
accepts_nested_attributes_for :user_skills, :allow_destroy => true, :reject_if => :all_blank
end
class UserSkill < ActiveRecord::Base
belongs_to :resume
has_and_belongs_to_many :technologies
end
class Technology < ActiveRecord::Base
has_and_belongs_to_many :user_skills
end
<%= nested_form_for([:student, @resume], validate: true, :html => { :multipart => true, class: "full-width" }) do |f| %>
------------------------------
Resume fields
------------------------------
<h5>User Skills</h5>
<%= f.fields_for :user_skills do |us| %>
<%= us.label :academic_years, "Academic Years" %>
<%= us.text_field :academic_years %>
<%= us.label :professional_years, "Professional Years" %>
<%= us.text_field :professional_years %>
<%= us.fields_for :technologies do |tech| %>
<%= tech.collection_select :name, Technology.all, :id, :name, { prompt: "Select Technology"}, { :multiple => true, :size => 10} %>
<% end %>
<%= us.link_to_remove "Remove", class: "btn btn-small red right" %>
答案 2 :(得分:0)
$stmt = $wpdb->query('SELECT * FROM '. $tablename);
$row_count = $stmt->rowCount();
if($row_count==1){
//drop table
}
else{
//alter table drop columns
}
希望有帮助。