[英]How to select Unknown Number of Columns in mysql?
給定表和某些列的名稱,我有以下信息模式選擇查詢。
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'm_college'
AND `TABLE_NAME` = 'm_fee'
AND COLUMN_NAME NOT IN ('id', 'classid', 'semid')
但是,此選擇不會為我提供我選擇的每個未知列的行值。 我所得到的只是未知列的名稱。 是否可以選擇行的值,以便在我的php腳本中可以將列作為鍵並將行作為值對? 我需要在其他表中插入列名和行值。 請幫助或建議。
SELECT * FROM table_name
選擇所有的列和它們的值的table_name
。 您使用的是從架構表中選擇所有列名(該表名不包含table_name
的信息)。
您可以在PHP中使用SELECT * FROM table_name
,而只需使用mysqli_fetch_assoc
即可獲得一個關聯數組,該數組基本上是一個key => value
array,其中key
是列名, value
是該數組在給定行中的值。
從PHP文檔( http://php.net/manual/en/mysqli-result.fetch-assoc.php )中提取目錄,因為您需要一個示例:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM table_name";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
下面是顯示相交表的非常快速的嘗試。
這使您擁有固定的結構並即時添加費用類型。
CREATE TABLE IF NOT EXISTS `mz_fee222` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`classid` int(11) NOT NULL,
`semid` int(11) NOT NULL,
`batch` year(4) NOT NULL,
`session` int(11) NOT NULL
);
create table fee_type
( fee_id int auto_increment primary key,
description varchar(100)
);
insert fee_type (description) values ('exam'),('marksheet'),('admitcard'),('centre'),('practical'); -- etc as you go
create table mz_fee_intersect
( -- here is where the fee amount is stored. Flexible.
id int auto_increment primary key,
mz_id int not null, -- this is the id from my_fee222 table
fee_id int not null, -- this is the fee_id from fee_type table
fee int not null, -- here is the actual fee, like 100 bucks
-- FK's below (not shown):
--
unique key (mz_id,fee_id) -- forbids duplicates
);
好的,我想不出為什么您有一個可以動態添加列的表,而不是顯而易見的表,但這對我有幫助
如果運行DESCRIBE tablename
並收集結果,則會得到類似以下的結果集。
Field Type Null Key Default Extra
id int(10) unsigned NO PRI NULL auto_increment
parent_id int(11) NO MUL 0
lft int(11) NO MUL 0
rgt int(11) NO 0
level int(10) unsigned NO NULL
name varchar(50) NO UNI NULL
title varchar(100) NO NULL
rules varchar(5120) NO NULL
如果將其加載到數組中,然后在以后的查詢中刪除您不想選擇的行,則可以得到它們的列名(在“字段”列中),甚至可以得到它們的數據類型。
然后,您可以使用此數組為特定列的查詢構建字段列表,並且您還知道在處理任何結果時要調用什么。
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.