这是我的表
sno | city | state | stateid
1 | chennai | tamilnadu | 1
2 | dindigul | tamilnadu | 1
3 | trivandrum | Kerala | 2
4 | cochin | Kerala | 2
我想这样显示(应该在升序时选择状态ID,并且应该显示城市仍然会到达更大的州议会大厦)
塔米尔纳杜
奈
丁迪古尔
喀拉拉
特里凡得琅
知
我怎样才能实现这个目标?
我到目前为止所尝试的是
(select city from (select * from state order by statid asc))
内部查询正在运行(通过stateid asc从状态顺序中选择*),但是当我使用(select city from (innerquery)
时。
投掷#1248 - Every derived table must have its own alias
我该如何解决这个问题?
答案 0 :(得分:2)
在PHP中执行:
<?php
$con = mysqli_connect("localhost", "root", "", "dbname");
$rs = $con->query('select city, state from mytable');
while ($row = $rs->fetch_array(MYSQLI_ASSOC)) {
$state_cities[$row['state']][] = $row['city'];
}
foreach ($state_cities as $state => $cities) {
echo "<b>".$state . "</b><br>";
foreach ($cities as $title) {
echo $title . "<br>";
}
}
?>
答案 1 :(得分:1)
(select city from (select * from state order by statid asc))
它需要表名称Where和字段名称与运算符。
(select city from <TableName> WHERE <FieldName> <Operator> (select * from state order by statid asc))
答案 2 :(得分:0)
我认为这不是一个正确的规范化表,因为state_name和id变得多余。如果有可能编辑表结构,您可以按以下方式分解表:
cities:
sno city_name state_id
1 chennai 1
2 dindigul 1
3 trivandrum 2
4 cochin 2
states:
state_id state_name
1 tamilnadu
2 kerala
然后您可以使用以下查询:
SELECT c.city_name,s.state_name FROM cities c INNER JOIN states s ON c.state_id = s.`state_id` ORDER BY c.state_id ASC;
SQL DUMP:
/*
SQLyog Ultimate v10.00 Beta1
MySQL - 5.5.24-log : Database - test
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `test`;
/*Table structure for table `cities` */
DROP TABLE IF EXISTS `cities`;
CREATE TABLE `cities` (
`sno` int(11) NOT NULL,
`city_name` varchar(100) NOT NULL,
`state_id` int(100) NOT NULL,
PRIMARY KEY (`sno`,`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `cities` */
insert into `cities`(`sno`,`city_name`,`state_id`) values (1,'chennai',1),(2,'dingi',1),(3,'cochin',2),(4,'efef',2);
/*Table structure for table `states` */
DROP TABLE IF EXISTS `states`;
CREATE TABLE `states` (
`state_id` int(11) NOT NULL,
`state_name` varchar(100) NOT NULL,
PRIMARY KEY (`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `states` */
insert into `states`(`state_id`,`state_name`) values (1,'tamilnadu'),(2,'kerala');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;