使用表连接丢失了对INFORMATION_SCHEMA.COLUMNS表的查询

时间:2018-05-06 21:33:03

标签: mysql metadata

我正在尝试将B. DOLINCT B.INDEX_NAME与B.COLUMN_NAME一起带回来。这就是我使用该群组的原因

然后对于返回的每一行,我需要A.DATA_TYPE

返回的A.DATA_TYPE不正确

SELECT  A.DATA_TYPE, B.INDEX_NAME,  B.COLUMN_NAME
FROM  INFORMATION_SCHEMA.COLUMNS as A, INFORMATION_SCHEMA.STATISTICS as B
where B.TABLE_SCHEMA= "mySchema"
and   B.TABLE_NAME  = "myTable"
and   A.TABLE_SCHEMA = B.TABLE_SCHEMA
and   A.TABLE_NAME   = B.TABLE_NAME
GROUP BY B.COLUMN_NAME

1 个答案:

答案 0 :(得分:0)

由于GROUP BY没有条件,因此DATA_TYPE子句会从返回的多个值中随机选择JOIN来引发您的问题。您需要做的是通过向JOIN添加条件将每列名称的值限制为1:

SELECT A.DATA_TYPE, B.INDEX_NAME, B.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS AS A
JOIN INFORMATION_SCHEMA.STATISTICS AS B
ON A.TABLE_SCHEMA = B.TABLE_SCHEMA AND
   A.TABLE_NAME = B.TABLE_NAME AND
   A.COLUMN_NAME = B.COLUMN_NAME
WHERE A.TABLE_SCHEMA= "mySchema" AND 
      A.TABLE_NAME  = "myTable"

在PHP中(使用MySQLI):

$sql = 'SELECT A.DATA_TYPE, B.INDEX_NAME, B.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS AS A
JOIN INFORMATION_SCHEMA.STATISTICS AS B
ON A.TABLE_SCHEMA = B.TABLE_SCHEMA AND
   A.TABLE_NAME = B.TABLE_NAME AND
   A.COLUMN_NAME = B.COLUMN_NAME
WHERE A.TABLE_SCHEMA= "mySchema" AND 
      A.TABLE_NAME  = "myTable"';
$result = mysqli_query($conn, $sql);
echo mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) print_r($row);