我需要一个查询(对于给定的表名)显示带有指示符的列列表,如果此列存在UNIQUE约束但是只有当此列是SINGLE COLUMN约束时,如果此列是多列约束的一部分,则不
例如,对于此表:
CREATE TABLE IF NOT EXISTS `prices` (
`priceId` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`motorcycleId` INT UNSIGNED NOT NULL,
`priceDatum` DATE NOT NULL,
`price` INT NOT NULL DEFAULT 0,
PRIMARY KEY (`priceId`),
INDEX `price_motorcycleId_fk_idx` (`motorcycleId` ASC),
UNIQUE INDEX `priceId_UNIQUE` (`priceId` ASC),
UNIQUE INDEX `price_UNIQUE` (`motorcycleId` ASC, `priceDatum` ASC),
CONSTRAINT `price_motorcycleId_fk`
FOREIGN KEY (`motorcycleId`)
REFERENCES `motorcycles` (`motorcycleId`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
此查询应该给出:
COLUMN |UNIQUE
============+======
priceId | Y
motorcycleId| N <-- should not be shown as UNIQUE since not single constraint
priceDatum | N <-- should not be shown as UNIQUE since not single constraint
price | N
答案 0 :(得分:0)
您不应该只检查是否存在这样的约束,而且还应检查该约束是否只有一列。因此,KEY_COLUMN_USAGE中该约束的计数应为1。
我目前无法测试它,但它看起来应该是这样的,以获得具有这种约束的列。您可以在子查询中执行类似的操作,或者只是在所有列的列表上连接此查询并检查:如果存在记录,则存在唯一的单列约束,否则不存在。
select
k.COLUMN_NAME
from
information_schema.KEY_COLUMN_USAGE k
join information_schema.TABLE_CONSTRAINTS tc
on k.TABLE_SCHEMA = tc.TABLE_SCHEMA
and k.TABLE_NAME = tc.TABLE_NAME
and k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
where
k.TABLE_NAME = 'prices'
and tc.CONSTRAINT_TYPE = 'UNIQUE'
group by
k.CONSTRAINT_CATALOG,
k.CONSTRAINT_SCHEMA,
k.CONSTRAINT_NAME
having
count(*) = 1
答案 1 :(得分:0)
The solution is:
$offset = array_search('status', array_keys($columns));
$payment_status = $columns['status'];
$result = array_merge(array_slice($columns, 0, $offset), array('payment_status' => $payment_status), array_slice($columns, $offset, null));
unset($result['status']);
print_r($result);