How to refer to a value in Sql View Query - mysql

--
-- Table structure for table `emp`
--
CREATE TABLE `emp` (
`Emp_id` int(11) NOT NULL,
`Name` varchar(30) DEFAULT NULL,
`Sup_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `emp`
--
INSERT INTO `emp` (`Emp_id`, `Name`, `Sup_id`) VALUES
(1, 'Mark 18', NULL),
(2, 'Iron Man', 1),
(3, 'Hulk', NULL),
(4, 'Ant-Man', 2);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `emp`
--
ALTER TABLE `emp`
ADD PRIMARY KEY (`Emp_id`),
ADD KEY `Sup_id` (`Sup_id`);
--
this is my table DESC
i want output as this
like in case of iron man
iwant out put like this
2 Iron Man Mark 18
this means it want to check the Emp_id and Dispaly correspond name of Emp _id
DESc Stucture
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Emp_id | int(11) | NO | PRI | NULL | |
| Name | varchar(30) | YES | | NULL | |
| Sup_id | int(11) | YES | MUL | NULL | |
+--------+-------------+------+-----+---------+-------+
Values Inside Table
+--------+----------+--------+
| Emp_id | Name | Sup_id |
+--------+----------+--------+
| 1 | Mark 18 | NULL |
| 2 | Iron Man | 1 |
| 3 | Hulk | NULL |
| 4 | Ant-Man | 2 |
+--------+----------+--------+
Output format i want
+--------+----------+--------+
| Emp_id | Name | Sup_id |
+--------+----------+--------+
| 1 | Mark 18 |NULL |
| 2 | Iron Man |MArk 18 |
| 3 | Hulk | NULL |
| 4 | Ant-Man |Iron Man|
+--------+----------+--------+

Just LEFT JOIN table on itself:
SELECT e.Emp_id, e.Name, es.Name AS Sup_name FROM emp AS e LEFT JOIN emp AS es ON e.Sup_id = es.Emp_id

Related

MySQL INSERT INTO ON DUPLICATE KEY UPDATE non sequential id

I have this table:
CREATE TABLE `test` (`id` INT(11) NOT NULL AUTO_INCREMENT , `name` VARCHAR(100) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
| id | name |
| -- | ---- |
In which I insert the following two rows:
INSERT INTO `test`(`name`) VALUES ('Oscar'), ('Alba')
| id | name |
| -- | ----- |
| 1 | Oscar |
| 2 | Alba |
Now, I want to update the existing rows and create new ones:
INSERT INTO `test` (`id`, `name`) VALUES (1, 'Oscar'), (2, 'Nadia'), ('', 'Pedro') ON DUPLICATE KEY UPDATE `id` = VALUES (`id`), `name` = VALUES (`name`)
| id | name |
| -- | ----- |
| 1 | Oscar |
| 2 | Nadia |
| 3 | Pedro |
If I update existing rows again and create new ones, this is what happens:
INSERT INTO `test` (`id`, `name`) VALUES (1, 'Oscar'), (2, 'Nadia'), (3, 'Lucas'), ('', 'Maria'), ('', 'Sergio') ON DUPLICATE KEY UPDATE `id` = VALUES (`id`), `name` = VALUES (`name`)
| id | name |
| -- | ------ |
| 1 | Oscar |
| 2 | Nadia |
| 3 | Lucas |
| 6 | Maria |
| 7 | Sergio |
There is a jump in the auto increment id. I don't know why this happens. I would like to know if there is any way to avoid this.

How to create an index on a CONCAT("string" ,column) in mysql?

I have a table where id is primary key.
CREATE TABLE t1 (
id INT NOT NULL AUTO_INCREMENT,
col1 VARCHAR(45) NULL,
PRIMARY KEY (id));
I have another table t2 which is joining table t1 as
t2 LEFT JOIN t1 ON CONCAT("USER_", t1.id) = t2.user_id
I want to create an index which has CONCAT("USER_", t1.id) values indexed in any order.
I tried
ALTER TABLE t1 ADD INDEX ((CONCAT('user_',id) DESC);
but it is giving error.
I have followed official documentation of mysql.
Note : I do not want to create a new CONCAT("user_", id) column.
https://dev.mysql.com/doc/refman/8.0/en/create-index.html#create-index-column-prefixes
InnoDB supports secondary indexes on virtual generated columns.
https://dev.mysql.com/doc/refman/5.7/en/create-table-secondary-indexes.html
In 5.7(onward) you can use a generated column, then index that column. e.g.
Here is an example of taking the integer out of the string to create an efficient join:
CREATE TABLE myusers (
id mediumint(8) unsigned NOT NULL auto_increment
, name varchar(255) default NULL,
PRIMARY KEY (`id`)
) AUTO_INCREMENT=1
;
INSERT INTO myusers (`name`) VALUES ('Imelda'),('Hamish'),('Brandon'),('Amity'),('Jillian'),('Lionel'),('Faith'),('Dai'),('Reed'),('Molly');
CREATE TABLE mytable (
id mediumint(8) unsigned NOT NULL auto_increment
, user_id VARCHAR(20)
, ex_user_id integer GENERATED ALWAYS AS (0+substring(user_id,6,20))
, password varchar(255)
, PRIMARY KEY (`id`)
, INDEX idx_ex_user_id (ex_user_id)
) AUTO_INCREMENT=1
;
INSERT INTO mytable (`user_id`,`password`) VALUES
('user_1','PYX68BIC9RD')
,('user_2','LPY07EIN0UA')
,('user_3','UGC24TKI3JL')
,('user_4','YQU18ALB8YA')
,('user_5','DEL56AGR6AD')
,('user_6','YQN87UOB0PO')
,('user_7','CPC15JFU6MC')
,('user_8','MWC40ZWD2EE')
,('user_9','HEB34QQH0UM')
,('user_10','GVP36PLP5PW')
;
select
*
from myusers
inner join mytable on myusers.id = mytable.ex_user_id
;
id | name | id | user_id | ex_user_id | password
-: | :------ | -: | :------ | ---------: | :----------
1 | Imelda | 1 | user_1 | 1 | PYX68BIC9RD
2 | Hamish | 2 | user_2 | 2 | LPY07EIN0UA
3 | Brandon | 3 | user_3 | 3 | UGC24TKI3JL
4 | Amity | 4 | user_4 | 4 | YQU18ALB8YA
5 | Jillian | 5 | user_5 | 5 | DEL56AGR6AD
6 | Lionel | 6 | user_6 | 6 | YQN87UOB0PO
7 | Faith | 7 | user_7 | 7 | CPC15JFU6MC
8 | Dai | 8 | user_8 | 8 | MWC40ZWD2EE
9 | Reed | 9 | user_9 | 9 | HEB34QQH0UM
10 | Molly | 10 | user_10 | 10 | GVP36PLP5PW
explain select
*
from myusers
inner join mytable on myusers.id = mytable.ex_user_id
;
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra
-: | :---------- | :------ | :--------- | :--- | :------------- | :------------- | :------ | :------------------------------------- | ---: | -------: | :----------
1 | SIMPLE | myusers | null | ALL | PRIMARY | null | null | null | 10 | 100.00 | null
1 | SIMPLE | mytable | null | ref | idx_ex_user_id | idx_ex_user_id | 5 | fiddle_HNTHMETRTFAHHKBIGWZM.myusers.id | 1 | 100.00 | Using where
db<>fiddle here
note the conversion of user_id from string to integer is "implicit":
To cast a string to a number, you normally need do nothing other than use the string value in numeric context:
https://dev.mysql.com/doc/refman/5.7/en/create-table-secondary-indexes.html

Creating a One to One and a One to Many relationship between tables in MySQL

I am preparing for an exam and I decided to do some example tasks I made up but I am stuck on one particular. Relationships. I have been hitting my head against the wall of SQL for 3-4 hours with little progress. I have 2 tables in which I want to create a one to one and a one to many relationships.
CREATE TABLE article (
price INT(30) NOT NULL,
published_on DATE NOT NULL
);
CREATE TABLE tag(
descption VARCHAR(30) NOT NULL,
priority INT(30) NOT NULL
);
CREATE TABLE category(
date_created_on DATE NOT NULL,
name VARCHAR(30) NOT NULL
);
INSERT INTO article VALUES (10.0, "2001-01-01", 0);
INSERT INTO article VALUES (20.0, "1992-05-08", 0);
INSERT INTO tag VALUES ("wtf", 1, 1);
INSERT INTO tag VALUES ("is this", 2, 2);
ALTER TABLE article ADD article_id INT(30) NOT NULL;
ALTER TABLE article ADD PRIMARY KEY(article_id);
ALTER TABLE article MODIFY article_id AUTO_INCREMENT;
ALTER TABLE tag ADD tag_id INT(30) NOT NULL;
ALTER TABLE tag ADD PRIMARY KEY(tag_id);
ALTER TABLE tag MODIFY tag_id AUTO_INCREMENT;
ALTER TABLE tag ADD FOREIGN KEY (tag_id) REFERENCES (article_id);
I want to make it so that one article has a one to one with article, then to make it so article has a one to many with category. I can't do the one to one to even try the one to many. Can you please give me some insight as to how to make it happen and how the relationships will work?
Here is the information from inside the database -
mysql> select * from Tag;
+-------------+----------+--------+
| description | priority | tag_id |
+-------------+----------+--------+
| wtf | 1 | 1 |
| is this | 2 | 2 |
+-------------+----------+--------+
mysql> select * from Article;
+-------+--------------+------------+
| price | published_on | article_id |
+-------+--------------+------------+
| 10 | 2001-01-01 | 7 |
| 20 | 1992-05-08 | 8 |
+-------+--------------+------------+
mysql> describe Article;
+--------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+----------------+
| price | decimal(30,0) | YES | | NULL | |
| published_on | date | YES | | NULL | |
| article_id | int(30) | NO | PRI | NULL | auto_increment |
+--------------+---------------+------+-----+---------+----------------+
mysql> describe Tag;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| description | varchar(30) | NO | | NULL | |
| priority | int(30) | NO | | NULL | |
| tag_id | int(30) | NO | PRI | NULL | |
+-------------+-------------+------+-----+---------+-------+ mysql> select * from Tag;
+-------------+----------+--------+
| description | priority | tag_id |
+-------------+----------+--------+
| wtf | 1 | 1 |
| is this | 2 | 2 |
+-------------+----------+--------+
mysql> select * from Article;
+-------+--------------+------------+
| price | published_on | article_id |
+-------+--------------+------------+
| 10 | 2001-01-01 | 7 |
| 20 | 1992-05-08 | 8 |
+-------+--------------+------------+
mysql> describe Article;
+--------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+----------------+
| price | decimal(30,0) | YES | | NULL | |
| published_on | date | YES | | NULL | |
| article_id | int(30) | NO | PRI | NULL | auto_increment |
+--------------+---------------+------+-----+---------+----------------+
mysql> describe Tag;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| description | varchar(30) | NO | | NULL | |
| priority | int(30) | NO | | NULL | |
| tag_id | int(30) | NO | PRI | NULL | |
+-------------+-------------+------+-----+---------+-------+
And this is the error I get for creating the foreign key:
mysql> ALTER TABLE Tag ADD FOREIGN KEY(tag_id) REFERENCES Article(article_id);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`exam_example`.`#sql-2836_1`,
CONSTRAINT `#sql-2836_1_ibfk_1` FOREIGN KEY (`tag_id`) REFERENCES `Article` (`article_id`))
CREATE TABLE article (
price INT(30) NOT NULL,
published_on DATE NOT NULL,
article_id INT(30) NOT NULL,
CONSTRAINT pk_article_id PRIMARY KEY(article_id)
);
CREATE TABLE tag(
descption VARCHAR(30) NOT NULL,
priority INT(30) NOT NULL,
tag_id INT(30) NOT NULL,
CONSTRAINT pk_tag_article PRIMARY KEY(tag_id),
CONSTRAINT fk_tag_article FOREIGN KEY(tag_id) REFERENCES article(article_id)
);
INSERT INTO article VALUES (10.0, "2001-01-01", 0);
INSERT INTO article VALUES (20.0, "1992-05-08", 1);
INSERT INTO tag VALUES ("wtf", 1, 1);
INSERT INTO tag VALUES ("is this", 2, 2);
This is a relationship one to one.
I'm saying here that the primary key of the tag is the same from article.

Start auto_increment value not working when populating table with data from another table in MySQL

I want to create a table with data from another table in order to set the id to a certain auto_increment start value.
This is the table I want to populate with data from another table:
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| city | varchar(255) | YES | | NULL | |
| state | varchar(255) | YES | | NULL | |
| state_id | int(11) | YES | | NULL | |
| city_slug | varchar(255) | YES | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
After executing this query:
alter table table_temp auto_increment = 40499;
If I do a dummy insert:
insert into table_temp (city, state, state_id, city_slug) values (1, 1, 1, 1);
It does what it's expected, that is, the id starts with the value 40499
select * from table_temp;
+-------+------+-------+----------+-----------+
| id | city | state | state_id | city_slug |
+-------+------+-------+----------+-----------+
| 40499 | 1 | 1 | 1 | 1 |
+-------+------+-------+----------+-----------+
After truncate the table and execute again the alter table query for auto_increment, I try to populate the same table with data from another table:
insert into table_temp (city, state, state_id, city_slug) select city, state, state_id, city_slug from final_location;
However the id starts with a default id value of 1:
select * from table_temp limit 10;
+----+---------+---------+----------+-------------------+
| id | city | state | state_id | city_slug |
+----+---------+---------+----------+-------------------+
| 1 | Abatiá | Paraná | 242 | all-cidade-abatia |
+----+---------+---------+----------+-------------------+
Any suggestions on how to fix this?
I've just found what was wrong, after truncating the table it seems to loose reference of the auto_increment start value. I had to execute again the alter table query in order to set the auto_increment value properly again:
alter table table_temp auto_increment = 40499;

Where to start with optimizing/adding indexes to speed up query?

I'm not really sure where to start with cutting down this query in the search section of my site so that it doesn't take so long. You run a search on a variety of tables, and get filtered results back mainly from the "Items" table, and currently it (and searched like it) take sometimes over 10 seconds. Part of the problem is that the php code that composes the sql is dirty as hell, of course, and I'm not used to having huge queries that I need to optimize in general, but what techniques can I use to determine where to add indexes in a query like this?
The query
SELECT
items.ItemId,
items.Name,
items.BrandCode,
items.BrandCategoryId,
items.CatalogPage,
items.PriceRetail,
items.PriceSell,
items.PriceHold,
items.Descr,
items.GenderId,
products.ImagetnURL,
products.FlagDefault,
products.ProductId,
products.Code AS ProductCode,
products.Name AS ProductName,
brands.Name AS BrandName,
items.FlagStatus AS ItemFlagStatus
FROM
items,
products,
brands,
productsizes,
searchsizechartsizes,
sizechartsizes
WHERE
items.ItemId = products.ItemId AND
items.BrandCode = brands.Code AND
items.FlagStatus != 'U' AND
products.FlagStatus != 'U' AND
items.TypeId = '10' AND
searchsizechartsizes.SearchSizeChartId = '11' AND
searchsizechartsizes.Size = sizechartsizes.Size AND
sizechartsizes.SizeChartId = productsizes.SizeChartId AND
productsizes.ProductId = products.ProductId
GROUP BY
items.ItemId
ORDER BY
items.Name
LIMIT
0, 15;
Logs show 14 second execution time, and 3 million rows examined
# Query_time: 14 Lock_time: 0 Rows_sent: 15 Rows_examined: 2901565
Summary of query results
+--------+----------------------+-----------+-----------------+-------------+-------------+-----------+-----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------+----------------------------+-------------+-----------+-------------+------------------------------------------+-------------------+----------------+
| ItemId | Name | BrandCode | BrandCategoryId | CatalogPage | PriceRetail | PriceSell | PriceHold | Descr | GenderId | ImagetnURL | FlagDefault | ProductId | ProductCode | ProductName | BrandName | ItemFlagStatus |
+--------+----------------------+-----------+-----------------+-------------+-------------+-
| 3376 | 10-inch Pull On Boot | RW | 2801 | 24 | 189.99 | 189.99 | 189.99 | Full grain brown leather - blah blah blah | 1 | images/rw/rw-2249tn.jpg | Y | 4345 | 2249 | Brown Full Grain Turbo Vegas Leather | Red Wing Work | A |
| 9340 | 11 | RR | NULL | 1 | 300.00 | 300.00 | 300.00 | The Engineer 11" boot from Red Wing Shoes� blah blah blah... | 1 | images/rr/rr-2990tn.jpg | Y | 16749 | 2990 | Black Harness Calfskin | Red Wing Heritage | A
~~~~~~ other results here redacted for space reasons ~~~~~~
15 rows in set (13.33 sec)
Explain of the query
mysql> explain SELECT items.ItemId, items.Name, items.BrandCode, items.BrandCategoryId, items.CatalogPage, items.PriceRetail, items.PriceSell, items.PriceHold, items.Descr, items.GenderId, products.ImagetnURL, products.FlagDefault, products.ProductId, products.Code as ProductCode, products.Name as ProductName, brands.Name as BrandName, items.FlagStatus as ItemFlagStatus FROM items, products, brands, productsizes, searchsizechartsizes, sizechartsizes WHERE items.ItemId = products.ItemId AND items.BrandCode = brands.Code AND items.FlagStatus != 'U' AND products.FlagStatus != 'U' AND items.TypeId = '10' AND (searchsizechartsizes.SearchSizeChartId = '11' AND searchsizechartsizes.Size = sizechartsizes.Size AND sizechartsizes.SizeChartId = productsizes.SizeChartId AND productsizes.ProductId = products.ProductId) group by items.ItemId ORDER BY items.Name LIMIT 0, 15;
+----+-------------+----------------------+--------+------------------------------------------------+-------------+---------+----------------------------------------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------------+--------+------------------------------------------------+-------------+---------+----------------------------------------+------+---------------------------------+
| 1 | SIMPLE | searchsizechartsizes | ref | PRIMARY,Size | PRIMARY | 4 | const | 2 | Using temporary; Using filesort |
| 1 | SIMPLE | brands | ALL | NULL | NULL | NULL | NULL | 40 | |
| 1 | SIMPLE | sizechartsizes | ref | Size,SizeChartId | Size | 33 | shermanbros.searchsizechartsizes.Size | 217 | Using where |
| 1 | SIMPLE | productsizes | ref | ProductId,SizeChartId | SizeChartId | 5 | shermanbros.sizechartsizes.SizeChartId | 17 | Using where |
| 1 | SIMPLE | products | eq_ref | PRIMARY,FlagStatus,flagstatusanddefault,ItemId | PRIMARY | 4 | shermanbros.productsizes.ProductId | 1 | Using where |
| 1 | SIMPLE | items | eq_ref | PRIMARY,BrandCode,TypeId,FlagStatus,ItemsIndex | PRIMARY | 4 | shermanbros.products.ItemId | 1 | Using where |
+----+-------------+----------------------+--------+------------------------------------------------+-------------+---------+----------------------------------------+------+---------------------------------+
6 rows in set (0.02 sec)
Structure of the items table
mysql> show create table items;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| items | CREATE TABLE `items` (
`ItemId` int(11) NOT NULL auto_increment,
`Code` varchar(25) default NULL,
`Name` varchar(100) default NULL,
`BrandCode` char(2) default NULL,
`CatalogPage` int(3) default NULL,
`BrandCategoryId` int(11) default NULL,
`TypeId` int(11) default NULL,
`StyleId` int(11) default NULL,
`GenderId` int(11) default NULL,
`PriceRetail` decimal(6,2) default NULL,
`PriceSell` decimal(6,2) default NULL,
`PriceHold` decimal(6,2) default NULL,
`Cost` decimal(6,2) default NULL,
`PriceNote` longtext,
`FlagTaxable` char(1) default NULL,
`FlagStatus` char(1) default NULL,
`FlagFeatured` char(1) default NULL,
`MaintFlagStatus` char(1) default NULL,
`Descr` longtext,
`DescrNote` longtext,
`ImagetnURL` varchar(50) default NULL,
`ImagefsURL` varchar(50) default NULL,
`ImagelsURL` varchar(50) default NULL,
`DateCreated` date NOT NULL default '0000-00-00',
`DateStatus` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`AdminNote` text,
PRIMARY KEY (`ItemId`),
KEY `BrandCode` (`BrandCode`),
KEY `Name` (`Name`),
KEY `TypeId` (`TypeId`),
KEY `StyleId` (`StyleId`),
KEY `GenderId` (`GenderId`),
KEY `FlagStatus` (`FlagStatus`),
KEY `ItemsIndex` (`TypeId`,`FlagStatus`,`ItemId`)
) ENGINE=MyISAM AUTO_INCREMENT=10216 DEFAULT CHARSET=latin1 |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Existing indexes on the items table
mysql> show indexes from items;
+-------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+-------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| items | 0 | PRIMARY | 1 | ItemId | A | 8678 | NULL | NULL | | BTREE | |
| items | 1 | BrandCode | 1 | BrandCode | A | 36 | NULL | NULL | YES | BTREE | |
| items | 1 | Name | 1 | Name | A | 8678 | NULL | NULL | YES | BTREE | |
| items | 1 | TypeId | 1 | TypeId | A | 17 | NULL | NULL | YES | BTREE | |
| items | 1 | StyleId | 1 | StyleId | A | 41 | NULL | NULL | YES | BTREE | |
| items | 1 | GenderId | 1 | GenderId | A | 3 | NULL | NULL | YES | BTREE | |
| items | 1 | FlagStatus | 1 | FlagStatus | A | 6 | NULL | NULL | YES | BTREE | |
| items | 1 | ItemsIndex | 1 | TypeId | A | 17 | NULL | NULL | YES | BTREE | |
| items | 1 | ItemsIndex | 2 | FlagStatus | A | 52 | NULL | NULL | YES | BTREE | |
| items | 1 | ItemsIndex | 3 | ItemId | A | 8678 | NULL | NULL | | BTREE | |
+-------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
10 rows in set (0.00 sec)
It seems to have an index on various columns already, but those indexes still leave it slow with regards to this search query. And one multi-index on typeid, flagstats, itemid that's there to optimize a seperate query.
And yeah, as you can see, the items table itself is a beast, which probably doesn't help.
Looking at your FROM and WHERE clauses:
FROM
items,
products,
brands,
productsizes,
searchsizechartsizes,
sizechartsizes
WHERE
items.ItemId = products.ItemId AND
items.BrandCode = brands.Code AND
items.FlagStatus != 'U' AND
products.FlagStatus != 'U' AND
items.TypeId = '10' AND
searchsizechartsizes.SearchSizeChartId = '11' AND
searchsizechartsizes.Size = sizechartsizes.Size AND
sizechartsizes.SizeChartId = productsizes.SizeChartId AND
productsizes.ProductId = products.ProductId
you have put all of the join logic into the WHERE clause, which is unhelpful when reading the query. Using explicit join syntax instead, we can rewrite as the following:
FROM
items
JOIN products ON items.ItemId = products.ItemId
JOIN brands ON items.BrandCode = brands.Code
JOIN productsizes ON products.ProductId = productsizes.ProductId
JOIN sizechartsizes ON sizechartsizes.SizeChartId = productsizes.SizeChartId
JOIN searchsizechartsizes ON sizechartsizes.Size = searchsizechartsizes.Size
WHERE
items.FlagStatus != 'U' AND
items.TypeId = '10' AND
products.FlagStatus != 'U' AND
searchsizechartsizes.SearchSizeChartId = '11'
This makes it more clear what is going on.
It seems like you have a good candidate index for this query in ItemsIndex. (By the way - the index on TypeID alone is redundant and should be dropped, because TypeID is a left prefix of ItemsIndex.) Unfortunately MySQL's query optimiser seems to think it makes more sense to do the join back-to-front, starting with table searchsizechartsizes. I'm not sure why it would do this, but I notice that table brands apparently has no usable keys defined on it. It might be a good idea to look into this.