Exclude title and content that are NULL before output in SQL - php

I have the following SQL query and want to exclude title and content that is null. I have tried with WHERE title IS NOT NULL, but obviously that didn't work for me and returns error: Syntax error or access violation.
The current query
SELECT * FROM entries ORDER BY id DESC LIMIT $postnumbers OFFSET $offset
What i tried
SELECT * FROM entries WHERE title IS NOT NULL ORDER BY id DESC LIMIT $postnumbers OFFSET $offset
What is the correct answer?
Table definition
entries
CREATE TABLE entries (
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(150) DEFAULT NULL,
content longtext,
category int(11) DEFAULT NULL,
status int(11) DEFAULT NULL,
keyword1 varchar(45) DEFAULT NULL,
keyword2 varchar(45) DEFAULT NULL,
likes varchar(45) DEFAULT NULL,
image varchar(45) DEFAULT NULL,
description` varchar(45) DEFAULT NULL,
owner int(30) DEFAULT 0,
page_views int(50) DEFAULT NULL,
time int(20) DEFAULT NULL,
maincategory int(10) DEFAULT NULL,
entriescol varchar(45) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=latin1

Related

How do i make my database auto-generate unique Certificate number that will also be auto-incremented for example 00001

I am creating a database that will store 'graduate details'. I have been able to set the ID to auto increment, Unique and also my primary key that start from 1...
I also want to make the certificate number field unique and auto-increment value in an increasing order that will start from 00001.
Please any help on how to go about this will be very appreciated. Thank you.
This is the MYSQL code for the database below;
CREATE TABLE IF NOT EXISTS `graduates` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`f_name` varchar(25) NOT NULL,
`l_name` varchar(25) NOT NULL,
`gender` varchar(6) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
`city` varchar(15) DEFAULT NULL,
`region` varchar(30) DEFAULT NULL,
`phone` varchar(15) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`certificate_number` int(50) NOT NULL AUTO_INCREMENT,
`programme` varchar(50) CHARACTER SET utf8mb4 NOT NULL,
`marks` int(10) NOT NULL,
`college_name` varchar(50) CHARACTER SET utf8mb4 NOT NULL,
`date_of_birth` date DEFAULT NULL,
`created_by` int(10) UNSIGNED NOT NULL DEFAULT 0,
`created_at` date DEFAULT NULL,
`updated_by` int(10) UNSIGNED NOT NULL DEFAULT 0,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `certificate_number` (`certificate_number`)
) ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=utf8;

Fname and last name in mysql, error displaying

i have a problem in my examination system. In the admin panel, in the results page displays the correct score but the firstname and the last name not. I dont know what to do.
Here is the code:
$result1=executeQuery("select s.nume_student,s.prenume_student,s.stdname,s.stdid, IFNULL((select sum(q.marks) from studentquestion as sq,question as q where q.qnid=sq.qnid and sq.testid=".$_REQUEST['testid']." and sq.stdid=st.stdid and sq.stdanswer=q.correctanswer),0) as om from studenttest as st, student as s where s.stdid=st.stdid and st.testid=".$_REQUEST['testid'].";" );
$result3=executeQuery("SELECT sq.stdid, sq.testid, COUNT(*) AS correctAnswers, SUM(q.marks) AS studentScore,(SELECT SUM(marks) FROM question WHERE testid=".$_REQUEST['testid'].") AS totalScore FROM question q, studentquestion sq WHERE sq.testid=".$_REQUEST['testid']." AND q.testid = sq.testid AND q.qnid = sq.qnid AND sq.answered = 'answered' AND q.correctanswer = sq.stdanswer GROUP BY sq.stdid");
without $result1 doesen't display anything
And here are the tables from database:
question table:
CREATE TABLE IF NOT EXISTS `question` (
`testid` bigint(20) NOT NULL DEFAULT '0',
`qnid` int(11) NOT NULL DEFAULT '0',
`question` varchar(500) DEFAULT NULL,
`optiona` varchar(100) DEFAULT NULL,
`optionb` varchar(100) DEFAULT NULL,
`optionc` varchar(100) DEFAULT NULL,
`optiond` varchar(100) DEFAULT NULL,
`correctanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
`marks` float(3,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
studentquestion table:
CREATE TABLE IF NOT EXISTS `studentquestion` (
`stdid` bigint(20) NOT NULL DEFAULT '0',
`testid` bigint(20) NOT NULL DEFAULT '0',
`qnid` int(11) NOT NULL DEFAULT '0',
`answered` enum('answered','unanswered','review') DEFAULT NULL,
`stdanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
student table:
CREATE TABLE IF NOT EXISTS `student` (
`stdid` bigint(20) NOT NULL,
`stdname` varchar(40) DEFAULT NULL,
`stdpassword` varchar(40) DEFAULT NULL,
`emailid` varchar(40) DEFAULT NULL,
`contactno` varchar(20) DEFAULT NULL,
`fname` varchar(40) DEFAULT NULL,
`lname` varchar(40) DEFAULT NULL,
`pincode` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
student test table:
CREATE TABLE IF NOT EXISTS `studenttest` (
`stdid` bigint(20) NOT NULL DEFAULT '0',
`testid` bigint(20) NOT NULL DEFAULT '0',
`starttime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`endtime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`correctlyanswered` int(11) DEFAULT NULL,
`status` enum('over','inprogress') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and test table:
CREATE TABLE IF NOT EXISTS `test` (
`testid` bigint(20) NOT NULL,
`testname` varchar(30) NOT NULL,
`testdesc` varchar(100) DEFAULT NULL,
`testdate` date DEFAULT NULL,
`testtime` time DEFAULT NULL,
`subid` int(11) DEFAULT NULL,
`testfrom` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`testto` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`duration` int(11) DEFAULT NULL,
`totalquestions` int(11) DEFAULT NULL,
`attemptedstudents` bigint(20) DEFAULT NULL,
`testcode` varchar(40) NOT NULL,
`tcid` bigint(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I resolved the same problem of here:
How to get sql WHERE statement auto update from localhost link
but i'm stucked here with fname and last name.
If your second query returns the correct student ids, you can just change it to add student names:
SELECT s.lastname, s.firstname, e.*
from
students s join (
... your second query ... ) e
on s.stdid=e.stdid
you can change your join type depends on what you want.
Thanks, but i resolved it like this:
SELECT ***s.fname, s.lname***, sq.stdid, sq.testid, COUNT(*) AS correctAnswers,
SUM(q.marks) AS studentScore,(SELECT SUM(marks) FROM question
WHERE testid=1) AS totalScore
FROM question q, studentquestion sq, ***student s***
WHERE sq.testid=1 AND q.testid = sq.testid
AND q.qnid = sq.qnid AND sq.answered = 'answered' ***and sq.stdid=s.stdid***
AND q.correctanswer = sq.stdanswer GROUP BY sq.stdid

Mysql LEFT Join on big data table

I have a table called "tables_data_info" where is stored some of the data relative to different tables. Data like "created time", "editing time", "editing user", "create by user id" etc. I'm using this table because there was a dynamic php script that generate it automatically.
But, when i have a huge number of record ( 15k in this case ) the query getting very very very slow, and take "minutes" to do his job! But i'm not selecting all 15k records, i'm limiting to select 10 records at all!
A simple query:
SELECT pd.id, pd.title, pd.sell_price, pd.available_qt, tdi.createtime, tdi.lastupdatetime, tdi.create_member_id, tdi.create_group_id, tdi.last_update_member_id, tdi.last_update_group_id FROM zd_products AS pd LEFT JOIN zd_tables_data_info AS tdi ON ( tdi.targetid = pd.id and tdi.table_name = 'products' ) ORDER by pd.title ASC LIMIT 0, 10
How can i run this query differently but more efficiently ?
Here the table structure:
zd_products
CREATE TABLE `zd_products` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(256) NOT NULL DEFAULT '',
`internalcode` varchar(256) DEFAULT NULL,
`ean13_jan_code` varchar(256) DEFAULT NULL,
`upc_code` varchar(11) DEFAULT NULL,
`active` tinyint(1) NOT NULL DEFAULT '0',
`status` varchar(12) NOT NULL DEFAULT 'new',
`product_tags` longtext,
`buy_price` double NOT NULL DEFAULT '0',
`sell_price` double NOT NULL DEFAULT '0',
`fiscal_tax_id` int(11) NOT NULL DEFAULT '0',
`box_width` double NOT NULL DEFAULT '0',
`box_height` double NOT NULL DEFAULT '0',
`box_depth` double NOT NULL DEFAULT '0',
`box_weight` double NOT NULL DEFAULT '0',
`shipment_extra_price` double NOT NULL DEFAULT '0',
`available_qt` int(11) NOT NULL DEFAULT '0',
`allow_purchase_out_stock` tinyint(1) NOT NULL DEFAULT '0',
`meta_title` varchar(256) DEFAULT NULL,
`meta_description` varchar(256) DEFAULT NULL,
`meta_keywords` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15730 DEFAULT CHARSET=utf8;
zd_tables_data_info
CREATE TABLE `zd_tables_data_info` (
`table_name` varchar(256) NOT NULL DEFAULT '',
`targetid` int(11) DEFAULT NULL,
`create_member_id` int(11) unsigned DEFAULT NULL,
`create_group_id` int(11) unsigned DEFAULT NULL,
`last_update_member_id` int(11) unsigned DEFAULT NULL,
`last_update_group_id` int(11) unsigned DEFAULT NULL,
`createtime` int(11) unsigned DEFAULT NULL,
`lastupdatetime` int(11) unsigned DEFAULT NULL,
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `INDEX` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19692 DEFAULT CHARSET=utf8;
Your data is not particularly big. Here is the query:
SELECT pd.id, pd.title, pd.sell_price, pd.available_qt,
tdi.createtime, tdi.lastupdatetime, tdi.create_member_id, tdi.create_group_id,
tdi.last_update_member_id, tdi.last_update_group_id
FROM zd_products pd LEFT JOIN
zd_tables_data_info tdi
ON tdi.targetid = pd.id and tdi.table_name = 'products'
ORDER by pd.title ASC
LIMIT 0, 10;
You can improve performance of this query with indexes. The two that come to mind are zd_products(title, id) and zd_tables_data_info(targetid, table_name). Try these and see if they help. You can create these indexes either in the create table statement (or alter table) or by using:
create index zd_products_title_id on zd_products(title, id);
create index zd_tables_data_info_targetid_table_name on zd_tables_data_info(targetid, table_name);
If not, put explain in front of your query and then edit your question with the resulting plan.

Speed up query (~1 million rows) on a complex table

first of all thanks for your time reading this.
I'm working on a PHP web application that deals with the following data, as of right now there is noticeable time when trying to retrieve data, especially when drilling down the options. The primary options right now are VehicleType, Make, Model, Year, InternetPrice and Mileage. There will eventually be even more columns being used. Other columns from this list are being used for displaying data throughout the page, as 10 records are displayed at one instance.
Table structure:
CREATE TABLE `vehicles` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`DealerID` int(6) DEFAULT NULL,
`VIN` varchar(17) DEFAULT NULL,
`StockNumber` varchar(10) DEFAULT NULL,
`Status` varchar(1) DEFAULT NULL,
`VehicleType` int(1) DEFAULT NULL,
`Year` int(4) DEFAULT NULL,
`Make` varchar(13) DEFAULT NULL,
`Model` varchar(24) DEFAULT NULL,
`Trim` varchar(35) DEFAULT NULL,
`Body` varchar(25) DEFAULT NULL,
`VehicleClass` varchar(50) DEFAULT NULL,
`VehicleCategory` varchar(6) DEFAULT NULL,
`Mileage` int(6) DEFAULT NULL,
`Transmission` varchar(24) DEFAULT NULL,
`EngineDisplacement` varchar(7) DEFAULT NULL,
`EngineSize` varchar(15) DEFAULT NULL,
`Induction` varchar(25) DEFAULT NULL,
`DriveTrain` varchar(3) DEFAULT NULL,
`FuelType` varchar(9) DEFAULT NULL,
`FuelEconomyCity` int(2) DEFAULT NULL,
`FuelEconomyHighway` int(2) DEFAULT NULL,
`FuelEconomyCombined` int(1) DEFAULT NULL,
`Doors` int(1) DEFAULT NULL,
`OEMColorCodeExterior` varchar(10) DEFAULT NULL,
`OEMColorCodeInterior` varchar(10) DEFAULT NULL,
`OEMColorNameExterior` varchar(49) DEFAULT NULL,
`OEMColorNameInterior` varchar(10) DEFAULT NULL,
`GenericColorExterior` varchar(35) DEFAULT NULL,
`GenericColorInterior` varchar(38) DEFAULT NULL,
`InternetPrice` int(6) DEFAULT NULL,
`ComparisonPrice` int(6) DEFAULT NULL,
`WholeSalePrice` varchar(10) DEFAULT NULL,
`MSRP` varchar(10) DEFAULT NULL,
`InternetSpecial` varchar(1) DEFAULT NULL,
`OemModelCode` varchar(12) DEFAULT NULL,
`HasWarranty` varchar(1) DEFAULT NULL,
`CertificationWarranty` int(3) DEFAULT NULL,
`WarrantyMonth` int(1) DEFAULT NULL,
`WarrantyMiles` int(1) DEFAULT NULL,
`CertificationNumber` varchar(7) DEFAULT NULL,
`ServiceContract` varchar(1) DEFAULT NULL,
`InServiceDate` varchar(19) DEFAULT NULL,
`CertificationDate` varchar(19) DEFAULT NULL,
`DateManufactured` varchar(19) DEFAULT NULL,
`DateCreated` varchar(19) DEFAULT NULL,
`DateUpdated` varchar(19) DEFAULT NULL,
`DateRemoved` varchar(19) DEFAULT NULL,
`DatePhotosUpdated` varchar(19) DEFAULT NULL,
`Photos` int(2) DEFAULT NULL,
`SuperSizePhotos` int(2) DEFAULT NULL,
`AddendumDetails` varchar(10) DEFAULT NULL,
`DepartmentComments` varchar(239) DEFAULT NULL,
`VehicleComments` varchar(1987) DEFAULT NULL,
`Options` varchar(2264) DEFAULT NULL,
`PurchasePayment` decimal(5,2) DEFAULT NULL,
`PurchaseDownPayment` decimal(6,2) DEFAULT NULL,
`PurchaseTerm` int(2) DEFAULT NULL,
`PurchaseDisclosure` varchar(10) DEFAULT NULL,
`PurchaseRate` decimal(3,2) DEFAULT NULL,
`LeasePayment` decimal(2,2) DEFAULT NULL,
`LeaseDownPayment` decimal(2,2) DEFAULT NULL,
`LeaseTerm` int(1) DEFAULT NULL,
`LeaseDisclosure` varchar(10) DEFAULT NULL,
`LeaseRate` decimal(2,2) DEFAULT NULL,
`LeaseResidual` decimal(2,2) DEFAULT NULL,
`Reserved1` varchar(10) DEFAULT NULL,
`Reserved2` varchar(10) DEFAULT NULL,
`Reserved3` varchar(10) DEFAULT NULL,
`Reserved4` varchar(10) DEFAULT NULL,
`Reserved5` varchar(10) DEFAULT NULL,
`Reserved6` varchar(10) DEFAULT NULL,
`sitecert` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `VIN` (`VIN`),
KEY `Make` (`Make`),
KEY `StockNumber` (`StockNumber`),
KEY `Model` (`Model`),
KEY `Trim` (`Trim`),
KEY `Body` (`Body`),
KEY `VehicleClass` (`VehicleClass`),
KEY `Transmission` (`Transmission`),
KEY `DealerID` (`DealerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=46527428 ;
And an example query:
SELECT *
FROM vehicles
WHERE Make = 'Audi'
AND VehicleType = '0'
AND Model = 'A4'
AND InternetPrice BETWEEN 0 AND 999999
AND Year BETWEEN 1983 AND 2015
AND Mileage > 0
AND DealerID IN ('AA'
,'156553'
,'229602'
,'160483'
,'2953'
,'161712'
,'228576'
,'228921'
,'7590'
,'20813'
,'158105'
,'160286'
,'164479'
,'164487'
,'182543'
,'158860'
,'186479'
,'227170'
,'226327'
)
ORDER BY sitecert DESC
,InternetPrice DESC
LIMIT 0, 10
Would anyone have any advice to optimize this query or table? Of course there is other code throughout the page but I've timed it down to this query that is causing the delay.
Thanks for your help!
UPDATE:
MySQL Explain:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE vehicles ref Make,Model,DealerID Model 75 const 1675 Using where; Using filesort
Year was updated to INT
Depending on your database, you should add indexes on the following fields:
Make
VehicleType
Model
InternetPrice
Year
Mileage
DealerId
Year should be DATE type, not text (INT also makes sense).
This should solve your problem.
My advices :
use a group by make
partition your table, columns might be of use (make,Year)
store your table in inndb engine instead of myisam and build your
self some clustered indexes to attend your predicates !
For such a case you have to read EXPLAIN results and tweak indexes accordingly.
However, for only 1600 rows to sort I wouldn't bother at all. If you still want to make it faster, it seems you need a combined key that would include a Model and a sitecert followed by price, both in a reverse order.
Means you have to have two additional columns where negative values of sitecert and price are stored. then buind an index on (Model,nsitecert, nInternetPrice) and order without DESC to eliminate a filesort
If you have search queries that involve no Model but any combination of parameters - then it's time to think of an external search engine like Sphinx Search.

MySQL Query Optimization (Takes way too long)

I use the following prepared statement:
SELECT *
FROM
c_members,c_users,c_positions,c_done_meetings
WHERE
c_positions.POS_ID=c_users.POS_ID
AND c_members.CLUB_ID = ?
AND USER_POINTS >= ?
AND USER_POINTS <= ?
AND c_users.POS_ID LIKE ?
AND MEM_ACADEMY LIKE ?
AND MEM_SEX LIKE ?
AND MEM_GRADELVL LIKE ?
AND MEM_GPA >= ?
AND MEM_GPA <= ?
AND MEM_ARCHIVE = 0
GROUP BY
c_members.MEM_ID, c_members.CLUB_ID
HAVING
SUM(c_done_meetings.MEDONE_ATTEND = 'u') >= 1
ORDER BY
USER_POINTS DESC
However this query takes 21.971405982971 seconds to load 111 records. When I remove "Having SUM(...)" clause, the performance is 100% better. Is there a way I could optimize it better?
Edit: (Table structures)
CREATE TABLE IF NOT EXISTS `c_done_meetings` (
`MEM_ID` int(11) NOT NULL,
`CLUB_ID` int(11) NOT NULL,
`MEETING_ID` int(11) NOT NULL,
`MEDONE_ATTEND` varchar(1) NOT NULL COMMENT 'E=excused, U=unexcused, P=present',
UNIQUE KEY `unique` (`MEM_ID`,`CLUB_ID`,`MEETING_ID`),
KEY `MEETING_ID` (`MEETING_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `c_members` (
`MEM_ID` int(11) NOT NULL,
`CLUB_ID` int(11) NOT NULL,
`MEM_FIRST` varchar(50) NOT NULL,
`MEM_MIDDLE` varchar(50) DEFAULT NULL,
`MEM_LAST` varchar(50) NOT NULL,
`MEM_SEX` tinyint(1) NOT NULL COMMENT '0-Male 1-Female',
`MEM_EMAIL` varchar(100) DEFAULT NULL,
`MEM_GRADELVL` int(11) NOT NULL,
`MEM_ACADEMY` varchar(50) DEFAULT '',
`MEM_GPA` double DEFAULT '0',
`MEM_ADDRESS` varchar(500) DEFAULT NULL,
`MEM_CITY` varchar(100) DEFAULT NULL,
`MEM_STATE` varchar(100) DEFAULT NULL,
`MEM_ZIP` int(11) DEFAULT NULL,
`MEM_TELEPHONE` varchar(25) DEFAULT NULL,
`MEM_AP` tinyint(1) NOT NULL,
`MEM_HONORS` tinyint(1) NOT NULL,
`MEM_ESOL` tinyint(1) NOT NULL,
`MEM_HISP` tinyint(1) NOT NULL,
`MEM_WHITE` tinyint(1) NOT NULL,
`MEM_MULTI` tinyint(1) NOT NULL,
`MEM_NATIVE` tinyint(1) NOT NULL,
`MEM_BLACK` tinyint(1) NOT NULL,
`MEM_ASIAN` tinyint(1) NOT NULL,
`MEM_EXTRA` varchar(10000) DEFAULT NULL,
`MEM_ARCHIVE` tinyint(1) NOT NULL DEFAULT '0',
UNIQUE KEY `MEM_ID` (`MEM_ID`,`CLUB_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `c_positions` (
`POS_ID` int(11) NOT NULL AUTO_INCREMENT,
`CLUB_ID` int(11) NOT NULL,
`POS_NAME` varchar(20) NOT NULL,
`POS_DESC` varchar(500) NOT NULL,
`POS_ADMIN` tinyint(1) NOT NULL,
`POS_ATN_VIEW` tinyint(1) NOT NULL,
`POS_ATN_CHKIN` tinyint(1) NOT NULL,
`POS_ATN_FINALIZE` tinyint(1) NOT NULL,
`POS_MEM_VIEW` tinyint(1) NOT NULL,
`POS_MEM_ADD` tinyint(1) NOT NULL,
`POS_MEM_EDIT` tinyint(1) NOT NULL,
`POS_POS_VIEW` tinyint(1) NOT NULL,
`POS_POS_ADD` tinyint(1) NOT NULL,
`POS_POS_EDIT` tinyint(1) NOT NULL,
`POS_MEET_VIEW` tinyint(1) NOT NULL,
`POS_MEET_ADD` tinyint(1) NOT NULL,
`POS_MEET_EDIT` tinyint(1) NOT NULL,
`POS_EVENT_VIEW` tinyint(1) NOT NULL,
`POS_EVENT_ADD` tinyint(1) NOT NULL,
`POS_EVENT_EDIT` tinyint(1) NOT NULL,
`POS_EVENT_UPDATE` tinyint(1) NOT NULL,
`POS_REPORT_VIEW` tinyint(1) NOT NULL,
`POS_ARCHIVE_VIEW` tinyint(1) NOT NULL,
`POS_ANNOUNCEMENTS` tinyint(1) NOT NULL,
`POS_WEB_CUSTOM` tinyint(1) NOT NULL,
PRIMARY KEY (`POS_ID`),
UNIQUE KEY `UNIQUE_NAME` (`CLUB_ID`,`POS_NAME`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
CREATE TABLE IF NOT EXISTS `c_users` (
`MEM_ID` int(11) NOT NULL,
`CLUB_ID` int(11) NOT NULL,
`USER_PIN` int(11) NOT NULL,
`USER_POINTS` double NOT NULL,
`POS_ID` int(11) NOT NULL,
`USER_ARCHIVE` tinyint(1) NOT NULL DEFAULT '0',
UNIQUE KEY `MEM_ID` (`MEM_ID`,`CLUB_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Edit 2:
Yes all ids are indexed, the SUM(...) >= # calculates the number of missed meetings. # is a parameter set by the user (I just hard coded a 1 for testing)
You need to have indexes an all fields used in the WHERE clause, on all fields on which the tables are joined (you need to explicitly state your join conditions as right now, you are getting a Cartesian join), on all fields used for grouping and all fields used for sorting.
The last problem is the HAVING clause there. You are not going to be able to use an index at all for that since it is a calculated value. If this is a query you will use often in the system (i.e. not just for reporting), you might consider adding a field you can use as a flag for this filtering purpose. Whenever you set c_done_meetings.MEDONE_ATTEND = 'u' in any of your queries, you could also set this flag for the member or user or whatever this is associated with so that you have an easy field to filter on in a WHERE clause.
Outside of that, you might actually gain better performance by getting a reduced list of users or members with that value of u in a subselect and then join using that subselect as a table.
EDIT:
After seeing your actual table structure, I can clearly see where you need to add indexes. I am also wondering why you have tables c_users and c_members with the same exact primary key. Why would these not just be a single table?
Some things that pop out at me:
You use like quite a lot. Try to do something with your php code so that this isn't necessary. For example, mem_sex has a limited number of choices. Make the front end a radio button or dropdown so you send a value where you can use = instead of like.
Two, if you add a sum() to the select clause, and the appropriate group by clause, it should run faster. It's worth a shot.
You can denormalise you tables and add field to c_members that represent your
SUM(c_done_meetings.MEDONE_ATTEND = 'u') >= 1
But you need to update that field always, when updating c_done_meetings (can be done with trigger)
Also try to avoid LIKE conditions. Use = insead (it is possible at least for SEX)

Categories