MySQL - Counting a count? - mysql

I'm trying to aggregate some data I've pulled from my MySQL db.
Query I'm using is:
SELECT `PUID`,`DROID_V`,`SIG_V`,`SPEED`,
COUNT(distinct IF(sourcelist.hasExtension=1,NAME,NULL)) as Ext,
COUNT(distinct IF(sourcelist.hasExtension=0,NAME,NULL)) as NoExt,
COUNT(distinct NAME) as `All`
FROM sourcelist, main_small
WHERE sourcelist.SourcePUID = 'My_Variable' AND main_small.NAME = sourcelist.SourceFileName
GROUP BY `PUID`,`DROID_V`,`SIG_V`,`SPEED` ORDER BY `DROID_V` ASC, `SIG_V` ASC, `SPEED`
And I wondered if there was a way of counting this result, so I can make a new table that would show me something like:
Every distinct PUID, (count of distinct DROID_V), (count of distinct Sig_V), (SUM of total hits for NAME) WHERE sourcelist.SourcePUID = 'My_Variable' AND main_small.NAME = sourcelist.SourceFileName
As you can see, I'm really not very good at SQL!
Source table:
CREATE TABLE `t1` (
`DROID_V` int(1) DEFAULT NULL,
`Sig_V` varchar(7) DEFAULT NULL,
`SPEED` varchar(4) DEFAULT NULL,
`ID` varchar(7) DEFAULT NULL,
`PARENT_ID` varchar(10) DEFAULT NULL,
`URI` varchar(10) DEFAULT NULL,
`FILE_PATH` varchar(68) DEFAULT NULL,
`NAME` varchar(17) DEFAULT NULL,
`METHOD` varchar(10) DEFAULT NULL,
`STATUS` varchar(14) DEFAULT NULL,
`SIZE` int(10) DEFAULT NULL,
`TYPE` varchar(10) DEFAULT NULL,
`EXT` varchar(4) DEFAULT NULL,
`LAST_MODIFIED` varchar(10) DEFAULT NULL,
`EXTENSION_MISMATCH` varchar(32) DEFAULT NULL,
`MD5_HASH` varchar(10) DEFAULT NULL,
`FORMAT_COUNT` varchar(10) DEFAULT NULL,
`PUID` varchar(15) DEFAULT NULL,
`MIME_TYPE` varchar(24) DEFAULT NULL,
`FORMAT_NAME` varchar(10) DEFAULT NULL,
`FORMAT_VERSION` varchar(10) DEFAULT NULL,
`INDEX` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`INDEX`)
) ENGINE=MyISAM AUTO_INCREMENT=960831 DEFAULT CHARSET=utf8
example records:
5;"v37";"slow";"10266";;"file:";"V1-FL425817.tif";"V1-FL425817.tif";"BINARY_SIG";"MultipleIdenti";"20603284";"FILE";"tif";"2008-11-03";;;;"fmt/7";"image/tiff";"Tagged Ima";"3";"191977"
5;"v37";"slow";"10268";;"file:";"V1-FL425817.tif";"V1-FL425817.tif";"BINARY_SIG";"MultipleIdenti";"20603284";"FILE";"tif";"2008-11-03";;;;"fmt/8";"image/tiff";"Tagged Ima";"4";"191978"
5;"v37";"slow";"10269";;"file:";"V1-FL425817.tif";"V1-FL425817.tif";"BINARY_SIG";"MultipleIdenti";"20603284";"FILE";"tif";"2008-11-03";;;;"fmt/9";"image/tiff";"Tagged Ima";"5";"191979"
5;"v37";"slow";"10270";;"file:";"V1-FL425817.tif";"V1-FL425817.tif";"BINARY_SIG";"MultipleIdenti";"20603284";"FILE";"tif";"2008-11-03";;;;"fmt/10";"image/tiff";"Tagged Ima";"6";"191980"

Sure just do something like
Select Count(*) From (Select * From SomeTable) adummynamesoSqlParserDoesntgetupset
so put your query in parentheses after FROM give it a unique name, and you can treat it like a table or a view.

Related

Simple subquery to slow on huge table

so I got a mysql database with 2 tables, one (sd_clients) with about 24k entries:
CREATE TABLE `sd_clients` (
`ms_id` varchar(10) NOT NULL,
`ms_share_id` varchar(10) NOT NULL,
`short_name` varchar(25) DEFAULT NULL,
`standard_name` varchar(75) DEFAULT NULL,
`legal_name` varchar(150) DEFAULT NULL,
`country` varchar(4) DEFAULT NULL,
`status` tinyint(1) DEFAULT NULL COMMENT '1=Paid Client | 2=Non-Paid Client',
`user_id` int(11) DEFAULT NULL,
`summary` text,
`sector` int(4) DEFAULT NULL,
`sub_sector` int(4) DEFAULT NULL,
`business_country` char(3) DEFAULT NULL,
`created_at` date DEFAULT NULL,
`is_paid` int(1) NOT NULL DEFAULT '0' COMMENT '0 = Non-Paid Client | 1=Paid Client',
`description_en` text,
`description_zh-hans` text,
`description_zh-hant` text,
`highlights_en` text,
`highlights_zh-hans` text,
`highlights_zh-hant` text,
`logo` varchar(255) DEFAULT NULL,
`summary_subsection_title_en` varchar(500) DEFAULT NULL,
`summary_subsection_title_zh-hans` varchar(500) DEFAULT NULL,
`summary_subsection_title_zh-hant` varchar(500) DEFAULT NULL,
`summary_subsection_text_en` text,
`summary_subsection_text_zh-hans` text,
`summary_subsection_text_zh-hant` text,
`summary_short_en` varchar(2000) DEFAULT NULL,
`summary_short_zh-hans` varchar(2000) DEFAULT NULL,
`summary_short_zh-hant` varchar(2000) DEFAULT NULL,
`other_information_en` text,
`other_information_zh-hans` text,
`other_information_zh-hant` text,
`change_percentage` decimal(10,3) DEFAULT NULL,
`id_sector` bigint(3) DEFAULT NULL,
`id_subsector` bigint(3) DEFAULT NULL,
`background_info_en` text,
`background_info_zh-hans` text,
`background_info_zh-hant` text,
`share_id_displayed` varchar(10) DEFAULT NULL,
PRIMARY KEY (`ms_id`) KEY_BLOCK_SIZE=1024,
UNIQUE KEY `ms_id` (`ms_id`) KEY_BLOCK_SIZE=1024,
KEY `share_id_displayed` (`share_id_displayed`) KEY_BLOCK_SIZE=1024
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8;
SET FOREIGN_KEY_CHECKS=1;
And another called sd_clients_daily_stocks, with about 50 million entries:
CREATE TABLE `sd_clients_daily_stocks` (
`ms_id` varchar(10) NOT NULL,
`ms_share_id` varchar(10) DEFAULT NULL,
`created_at` date DEFAULT NULL,
`symbol` varchar(32) DEFAULT NULL,
`exchange_id` char(5) DEFAULT NULL,
`volume` bigint(18) DEFAULT NULL,
`day_low` decimal(19,6) DEFAULT NULL,
`day_high` decimal(19,6) DEFAULT NULL,
`market_cap` bigint(18) DEFAULT NULL,
`open_price` decimal(19,6) DEFAULT NULL,
`close_price` decimal(19,6) DEFAULT NULL,
`enterprise_value` bigint(18) DEFAULT NULL,
`currency_id` char(3) DEFAULT NULL,
`valoren` varchar(20) DEFAULT NULL,
`cusip` char(9) DEFAULT NULL,
`isin` varchar(12) DEFAULT NULL,
`sedol` varchar(7) DEFAULT NULL,
`ipo_date` date DEFAULT NULL,
`is_depositary_receipt` tinyint(1) DEFAULT NULL,
`depositary_receipt_ratio` decimal(9,4) DEFAULT NULL,
`security_type` char(10) DEFAULT NULL,
`share_class_description` varchar(1000) DEFAULT NULL,
`share_class_status` char(1) DEFAULT NULL,
`is_primary_share` tinyint(1) DEFAULT NULL,
`is_dividend_reinvest` tinyint(1) DEFAULT NULL,
`is_direct_invest` tinyint(1) DEFAULT NULL,
`investment_id` char(10) DEFAULT NULL,
`ipo_offer_price` decimal(19,6) DEFAULT NULL,
`delisting_date` date DEFAULT NULL,
`delisting_reason` varchar(100) DEFAULT NULL,
`mic` char(10) DEFAULT NULL,
`common_share_sub_type` varchar(32) DEFAULT NULL,
`ipo_offer_price_range` varchar(32) DEFAULT NULL,
`exchange_sub_market_global_id` char(10) DEFAULT NULL,
`conversion_ratio` decimal(19,9) DEFAULT NULL,
KEY `ms_id` (`ms_id`) USING HASH,
KEY `ms_share_id` (`ms_share_id`) USING HASH,
KEY `symbol` (`symbol`),
KEY `exchange_id` (`exchange_id`),
KEY `created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET FOREIGN_KEY_CHECKS=1;
I'm trying to run a fairly simple query:
SELECT DISTINCT
sd_clients.ms_id,
sd_clients.standard_name,
sd_clients.is_paid,
sd_clients.logo,
sd_clients.change_percentage,
(
SELECT
CONCAT(
`exchange_id`, '|--|',
`symbol`, '|--|',
`close_price`, '|--|',
`day_low`, '|--|',
`day_high`
) as items
FROM sd_clients_daily_stocks
WHERE ms_share_id = sd_clients.share_id_displayed
ORDER BY created_at DESC
LIMIT 1
) as company_data
FROM sd_clients
GROUP BY ms_id
ORDER BY sd_clients.standard_name ASC
LIMIT 10
But for some reason, it's taking way too long (like over 1 minute), to get any results, any idea why?
BTW, it works just fine if I remove the subquery, but I need it because the rest of the data, is in another table. Also, I know I could get the results without the subquery first, but I have other queries where the subquery must be there.
I also noticed that it gets blazing fast if I use a string instead of "sd_clients.share_id_displayed" on the subquery.
You should try an index on sd_clients_daily_stocks(ms_share_id, created_at).
You can add the additional columns from the select if you want a covering index.
You would probably be better off joining on a non-correlated subquery based off your current subquery; using this kind of technique here to find the most recent rows for each in the new subquery.
Edit: I was thinking more something like this:
SELECT DISTINCT sd_clients.ms_id, sd_clients.standard_name, sd_clients.is_paid, sd_clients.logo, sd_clients.change_percentage
, scdsB.items
FROM sd_clients
INNER JOIN (
SELECT scdsA.ms_share_id
, CONCAT(
scdsA.`exchange_id`, '|--|', scdsA.`symbol`, '|--|',
scdsA.`close_price`, '|--|', scdsA.`day_low`, '|--|', scdsA.`day_high`
) as items
FROM sd_clients_daily_stocks AS scdsA
INNER JOIN (
SELECT ms_share_id, MAX(created_at)
FROM sd_clients_daily_stocks
GROUP BY ms_share_id
) AS lasts
ON scdsA.ms_share_id = lasts.ms_share_id
AND scdsA.created_at = lasts.created_at
) scdsB
ON sd_clients.share_id_displayed = scdsB.ms_share_id
GROUP BY sd_clients.ms_id
ORDER BY sd_clients.standard_name ASC
LIMIT 10;
... But even this likely won't reduce the speed much more, if any, from the 12 seconds. At that point you are better off looking into indexes that could help. For example, the lasts grouping subquery that finds the most recent(max) created_at value for each ms_share_id value would benefit from an index on sd_clients_daily_stocks (ms_shared_id, created_at) as would the the JOIN it is used in.

SQL UNION with Where clause a result of the first select

I need to execute the following query:
SELECT (COL1,COL2, ClientID)
FROM Jobs
Union
SELECT (ClientID,COL2,COL3)
FROM Clients WHERE (the ClientID= ClientID my first select)
I'm really stuck, I've been trying joins and unions and have no idea how to do this.
*EDIT*Query to create jobs table
CREATE TABLE IF NOT EXISTS `jobs` (
`JobID` int(11) NOT NULL AUTO_INCREMENT,
`Title` varchar(32) NOT NULL,
`Trade` varchar(32) NOT NULL,
`SubTrade` varchar(300) NOT NULL,
`Urgency` tinyint(4) NOT NULL,
`DatePosted` int(11) NOT NULL,
`Description` varchar(500) NOT NULL,
`Photo` longblob,
`Photo2` longblob,
`Address` varchar(600) NOT NULL,
`ShowAddress` tinyint(4) NOT NULL,
`ShowExact` tinyint(4) NOT NULL,
`JobStatus` tinyint(4) NOT NULL,
`Longitude` double NOT NULL,
`Latitude` double NOT NULL,
`ClientID` int(11) NOT NULL,
`TradesmanID` int(11) DEFAULT NULL,
PRIMARY KEY (`JobID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=171 ;
and query to create clients table is
CREATE TABLE IF NOT EXISTS `clients` (
`ClientID` int(11) NOT NULL AUTO_INCREMENT,
`FName` varchar(32) NOT NULL,
`SName` varchar(32) NOT NULL,
`Email` varchar(32) NOT NULL,
`HomePhone` int(11) NOT NULL,
`Mobile` varchar(30) NOT NULL,
`Address` varchar(100) NOT NULL,
`County` varchar(32) NOT NULL,
`PostCode` varchar(32) NOT NULL,
`UserName` varchar(32) NOT NULL,
`Password` varchar(32) NOT NULL,
`NotificationID` varchar(255) NOT NULL,
PRIMARY KEY (`ClientID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=96 ;
SELECT
Clients.ClientID
,Clients.NotificationID
,Clients.Email
,Clients.Mobile
,Clients.HomePhone
,Jobs.JobID
,Jobs.Title
,Jobs.Trade
,Jobs.Address AS JobAddress
,Jobs.Urgency
,Jobs.DatePosted
,Jobs.Description
,Jobs.Photo
,Jobs.Photo2
,Jobs.ShowAddress
,Jobs.ShowExact
,Jobs.JobStatus
,Jobs.TradesmanID
,Jobs.Longitude
,Jobs.Latitude
FROM
Clients
INNER JOIN
Jobs
on Clients.ClientId = Jobs.ClientId
How about this? There is a bit of duplication i.e. the select clause in the second union replications the first statement but it will work.
SELECT COL1,COL2, ClientID
FROM Jobs
Union
SELECT ClientID,COL2,COL3
FROM Clients WHERE (Select ClientID FROM Jobs)
try this:
SELECT c.ClientID, c.COL2, c.COL3, x.col1
FROM Clients c inner join
(select clientId,
min(col1) as col1
from jobs
group by clientId) x
on c.clientId = x.clientId

create table from two existing table by making the index column and value not match in both table

for this table1 structure is:
CREATE TABLE `table1` (
`table_id` int(11) NOT NULL auto_increment,
`firstname` varchar(25) default NULL,
`column2` varchar(32) default NULL,
`column3` varchar(25) default NULL,
`column4` varchar(25) default NULL,
`column5` varchar(56) default NULL,
`column6` varchar(25) default NULL,
`column7` varchar(36) default NULL,
`column8` varchar(25) default NULL,
`column9` varchar(40) default NULL,
`column10` varchar(86) default NULL,
`column11` varchar(113) default NULL,
`column12` varchar(50) default NULL,
`column13` varchar(50) default NULL,
`column14` varchar(25) default NULL,
`column15` varchar(25) default NULL,
`column16` varchar(25) default NULL,
`column17` varchar(25) default NULL,
`column18` varchar(25) default NULL,
PRIMARY KEY (`table_id`),
KEY `firstname` (`firstname`),
) ENGINE=MyISAM AUTO_INCREMENT=13982 DEFAULT CHARSET=utf8;
CREATE TABLE `table2` (
`table_id` int(11) NOT NULL auto_increment,
`firstname` varchar(25) default NULL,
`column2` varchar(32) default NULL,
`column3` varchar(25) default NULL,
`column4` varchar(25) default NULL,
`column5` varchar(56) default NULL,
`column6` varchar(25) default NULL,
`column7` varchar(36) default NULL,
`column8` varchar(25) default NULL,
`column9` varchar(40) default NULL,
`column10` varchar(86) default NULL,
`column11` varchar(113) default NULL,
`column12` varchar(50) default NULL,
`column13` varchar(50) default NULL,
`column14` varchar(25) default NULL,
`column15` varchar(25) default NULL,
`column16` varchar(25) default NULL,
`column17` varchar(25) default NULL,
`column18` varchar(25) default NULL,
PRIMARY KEY (`table_id`),
KEY `firstname` (`firstname`),
) ENGINE=MyISAM AUTO_INCREMENT=13982 DEFAULT CHARSET=utf8;
after this executing this below query and its giving timeout expired in code.
CREATE TABLE new_tablematch
select table_id, firstname
from table1
where firstname NOT in (select a.firstname
from table1 as a , table2 as b
where a.firstname= b.firstname);
Try this query:
CREATE TABLE new_tablematch
SELECT table1.table_id, table1.firstname
FROM table1 LEFT JOIN table2 ON table1.firstname = table2.firstname
WHERE table2.firstname IS NULL;
It should have a better performance than your query (you are referring to table1 twice, and the subselect might be executed for every row of table1).
The problem with your query is that you mention table1 twice. It is not needed in the subquery:
CREATE TABLE new_tablematch
select table_id, firstname
from table1
where firstname NOT in (select b.firstname
from table2 as b
);
However, the join version in the other answer might perform even better.

MySQL IN Statement Hang

What I'm attempting to accomplish is return a SELECT statement of ALL duplicates in a table within given filters.
I'm attempting to run the following query but every time I run it my server locks up and it never completes the query. I have no idea what is causing this and some help would be greatly appreciated on either how to fix this or to accomplish my goal in another manner.
EDIT: I've added the EXPLAIN data as requested!
EDIT 2: I've added the CREATE statements as requested!
SELECT *
FROM red_flags
WHERE customer_number IN (SELECT customer_number
FROM red_flags
GROUP BY customer_number
HAVING COUNT(customer_number) > 1);
Execution plan:
1 PRIMARY leads ALL 80708 Using where
1 PRIMARY customers eq_ref PRIMARY PRIMARY 9 apcard_main.leads.customer_number 1
2 DEPENDENT SUBQUERY leads ALL 80708 Using where; Using temporary; Using filesort
2 DEPENDENT SUBQUERY customers eq_ref PRIMARY PRIMARY 9 apcard_main.leads.customer_number 1 Using index
DDL:
Table customers:
CREATE TABLE `customers` (
`customer_number` varchar(7) NOT NULL,
`dealer_id` varchar(32) DEFAULT NULL,
`first_name` varchar(64) DEFAULT NULL,
`middle_name` varchar(64) DEFAULT NULL,
`last_name` varchar(64) DEFAULT NULL,
`address_one` varchar(128) DEFAULT NULL,
`address_two` varchar(128) DEFAULT NULL,
`city` varchar(128) DEFAULT NULL,
`state` varchar(32) DEFAULT NULL,
`zip` char(5) DEFAULT NULL,
`fico` char(3) DEFAULT NULL,
`phone` varchar(13) DEFAULT NULL,
`mail_type` varchar(32) DEFAULT NULL,
`mail_date` date DEFAULT NULL,
`store` varchar(32) DEFAULT NULL,
PRIMARY KEY (`customer_number`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1$$
Table leads:
CREATE TABLE `leads` (
`lead_id` int(11) NOT NULL AUTO_INCREMENT,
`dealer_id` varchar(32) DEFAULT NULL,
`customer_number` varchar(7) DEFAULT NULL,
`date` date DEFAULT NULL,
`time` time DEFAULT NULL,
`source` varchar(32) DEFAULT NULL,
`source_type` varchar(32) DEFAULT NULL,
`home_phone` varchar(13) DEFAULT NULL,
`email` varchar(64) DEFAULT NULL,
`mail_type` varchar(8) DEFAULT NULL,
`store` varchar(16) DEFAULT NULL,
`first_name` varchar(64) DEFAULT NULL,
`last_name` varchar(64) DEFAULT NULL,
`middle_name` varchar(32) DEFAULT NULL,
`city` varchar(128) DEFAULT NULL,
`state` varchar(32) DEFAULT NULL,
`zip` char(5) DEFAULT NULL,
`fico` char(3) DEFAULT NULL,
`mail_date` date DEFAULT NULL,
`work_phone` varchar(13) DEFAULT NULL,
`cell_phone` varchar(13) DEFAULT NULL,
`address_one` varchar(128) DEFAULT NULL,
`address_two` varchar(128) DEFAULT NULL,
`comment` varchar(255) DEFAULT NULL,
`caller_id` varchar(128) DEFAULT NULL,
PRIMARY KEY (`lead_id`)
) ENGINE=MyISAM AUTO_INCREMENT=125587 DEFAULT CHARSET=latin1$$
View red_flags:
CREATE
ALGORITHM=UNDEFINED
DEFINER=`apcard`#`97.83.30.118`
SQL SECURITY DEFINER
VIEW `red_flags` AS
select
`leads`.`dealer_id` AS `dealer_id`,
`customers`.`phone` AS `phone`,
`leads`.`date` AS `date`,
`leads`.`time` AS `time`,
`leads`.`source` AS `source`,
`leads`.`customer_number` AS `customer_number`,
`leads`.`caller_id` AS `caller_id`,
`leads`.`mail_type` AS `mail_type`,
`leads`.`store` AS `store`,
`leads`.`last_name` AS `last_name`,
`leads`.`first_name` AS `first_name`,
`leads`.`city` AS `city`,
`leads`.`state` AS `state`,
`leads`.`zip` AS `zip`,
`leads`.`fico` AS `fico`,
`leads`.`mail_date` AS `mail_date`,
`leads`.`home_phone` AS `home_phone`,
`leads`.`email` AS `email`
from (`customers` join `leads`)
where ((`customers`.`customer_number` = `leads`.`customer_number`)
and (`leads`.`date` >= (now() - interval 30 day)))$$
Have you tried joining rather than using a subquery?
SELECT rf.*
FROM red_flags rf
inner join red_flags rf2
on (rf2.customer_number = rf.customer_number)
group by rf2.customer_number
having count(rf2.customer_number) >1
I figured it out, I had a poorly formed date filter that was causing it to break when querying with an IN for some reason.
leads.date >= now() - INTERVAL 30 DAY

sql statement mysql notcorrect

SELECT SUBSTRING(m.own,3,4) as c , (select amphur.AMPHUR_NAME where c = SUBSTRING(m.own,3,4) ),
COUNT(* ) AS cnt
FROM MEMBER AS m
GROUP BY SUBSTRING(m.own,3,4)
order by cnt desc
sql statement mysql
what wrong with code below when i fill
(select amphur.AMPHUR_NAME where c = SUBSTRING(m.own,3,4) )
it error
CREATE TABLE IF NOT EXISTS `member` (
`idmember` int(11) NOT NULL AUTO_INCREMENT,
`own` varchar(255) DEFAULT NULL,
`Sname` varchar(255) DEFAULT NULL,
`Ssurname` varchar(255) DEFAULT NULL,
`Sex` enum('¿','¿') NOT NULL,
`Hno` varchar(255) DEFAULT NULL,
`Moo` varchar(255) DEFAULT NULL,
`tambol` varchar(200) NOT NULL,
`dateofbirth` date DEFAULT NULL,
`migratedate` date DEFAULT NULL,
`status` enum('5','4','3','2','1') DEFAULT '5',
`Unit` int(4) DEFAULT NULL,
`staff1` int(11) DEFAULT NULL,
`staff2` int(11) DEFAULT NULL,
`fathercode` varchar(30) NOT NULL,
`mathercode` varchar(30) NOT NULL,
PRIMARY KEY (`idmember`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=8994 ;
CREATE TABLE IF NOT EXISTS `amphur` (
`AMPHUR_ID` int(5) NOT NULL AUTO_INCREMENT,
`AMPHUR_CODE` varchar(4) COLLATE utf8_unicode_ci NOT NULL,
`AMPHUR_NAME` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
`GEO_ID` int(5) NOT NULL DEFAULT '0',
`PROVINCE_ID` int(5) NOT NULL DEFAULT '0',
`province_name` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`AMPHUR_ID`),
KEY `province_name` (`province_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=999 ;
Your subquery is missing a From clause:
SELECT SUBSTRING(m.own,3,4) as c
, (select amphur.AMPHUR_NAME
From amphur
Where ??? = SUBSTRING(m.own,3,4) )
, COUNT(* ) AS cnt
FROM MEMBER AS m
However, how does the amphur table relate to the member table?
You cannot use aliases in the same level.
Even if you could, you are filtering on non-correlated columns in your subquery: the subquery would just return the record from amphur if there is one record, or an error if there are more.
Could you please provide some sample data and the desired recordset?
there is no "FROM" clause in your select Amphur.amphur_name