Hello i have one query with inner join that take a question and 4 answers from the db. I want to make this query to take only the questions that lang table is 'en'
This is the query:
$mysql->query("SELECT Q.id AS id, Q.question, QA.answer1, QA.answer2,
QA.answer3, QA.answer4, QA.correct, QC.name AS cat_name
FROM question Q
INNER JOIN question_answers QA ON QA.questionFK=Q.id
INNER JOIN question_cats QC ON QC.id=Q.categoryFK
ORDER BY rand()
LIMIT 1");
I try to make it like this:
$mysql->query("SELECT Q.id AS id, Q.question, QA.answer1, QA.answer2,
QA.answer3, QA.answer4, QA.correct, QC.name AS cat_name
FROM question Q
INNER JOIN question_answers QA ON QA.questionFK=Q.id
INNER JOIN question_cats QC ON QC.id=Q.categoryFK
WHERE Q.lang='en'
ORDER BY rand()
LIMIT 1");
But it didn't work, it's select everyting...
Where am i wrong and how should i make it?
Those are the 2 tables:
CREATE TABLE IF NOT EXISTS `question` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`question` varchar(255) NOT NULL,
`cnt` int(10) NOT NULL DEFAULT '0',
`correct` int(10) NOT NULL DEFAULT '0',
`categoryFK` int(3) NOT NULL DEFAULT '0',
`from_userFK` int(10) NOT NULL DEFAULT '0',
`correct_points` int(10) DEFAULT NULL,
`ut` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`del` enum('yes','no') NOT NULL DEFAULT 'no',
`lang` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=26 ;
CREATE TABLE IF NOT EXISTS `question_answers` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`questionFK` int(10) NOT NULL,
`answer1` varchar(255) CHARACTER SET cp1251 NOT NULL,
`answer2` varchar(255) CHARACTER SET cp1251 NOT NULL,
`answer3` varchar(255) CHARACTER SET cp1251 NOT NULL,
`answer4` varchar(255) CHARACTER SET cp1251 NOT NULL,
`correct` int(1) NOT NULL,
`ut` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`del` enum('yes','no') CHARACTER SET cp1251 NOT NULL DEFAULT 'no',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=25 ;
To me it feels like your filer condition WHERE Q.lang='en' doesn't matches any record and so the outcome. Consider trimming it before comparing like
WHERE TRIM(Q.lang) ='en'
Related
I'm getting weird results from my query. The numbers are way off and I can't figure out why.
Heres the table structure for the tables used in the query:
CREATE TABLE IF NOT EXISTS `bookings` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`customer_id` int(11) DEFAULT NULL,
`payment_method_id` int(11) DEFAULT NULL,
`date` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`time` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`details` text COLLATE utf8mb4_unicode_ci,
`ip` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`status` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'Complete',
`booked_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `booking_products` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`booking_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`amount` int(11) NOT NULL,
`price_subtotal` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`price_total` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `booking_services` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`booking_id` int(11) NOT NULL,
`service_id` int(11) NOT NULL,
`reservations` int(11) NOT NULL,
`price_subtotal` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`price_total` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `payment_methods` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `payment_methods_name_unique` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Here is my query:
return DB::table('bookings')
->selectRaw('payment_methods.name, count(bookings.id) as bookings, (sum(booking_services.price_subtotal) + sum(booking_products.price_subtotal)) as subtotal')
->join('booking_services', 'booking_services.booking_id', '=', 'bookings.id')
->join('booking_products', 'booking_products.booking_id', '=', 'bookings.id')
->join('payment_methods', 'payment_methods.id', '=', 'bookings.payment_method_id')
->where('bookings.status', 'Complete')
->whereBetween('bookings.booked_at', [$this->carbon_from, $this->carbon_to])
->groupBy('payment_methods.id')
->orderBy('payment_methods.name')
->get();
$this->carbon_from and $this->carbon_to are carbon objects which work fine.
I'm trying to obtain the total bookings and a sum of the price_subtotals for each payment method. It seems to be grouping the booking products/services together rather than by each payment method like I want.
Am I missing something here?
Edit: here is the query log:
select payment_methods.name,
count(bookings.id) as bookings,
(sum(booking_services.price_subtotal) + sum(booking_products.price_subtotal)) as subtotal
from `bookings`
inner join `booking_services` on `booking_services`.`booking_id` = `bookings`.`id`
inner join `booking_products` on `booking_products`.`booking_id` = `bookings`.`id`
inner join `payment_methods` on `payment_methods`.`id` = `bookings`.`payment_method_id`
where `bookings`.`status` = ? and `bookings`.`booked_at` between ? and ?
group by `payment_methods`.`id`
order by `payment_methods`.`name` asc
I guess you are getting cross product that is why you are getting wrong numbers for aggregation, what i suggest you, calculate your sum in individual sub clauses and then join these clauses with your main query like
SELECT p.name,
COUNT(DISTINCT b.id) AS bookings,
bs.price_subtotal + bp.price_subtotal AS subtotal
FROM bookings b
INNER JOIN (
SELECT booking_id, SUM(price_subtotal) price_subtotal
FROM booking_services
GROUP BY booking_id
) bs ON b.id = bs.booking_id
INNER JOIN (
SELECT booking_id, SUM(price_subtotal) price_subtotal
FROM booking_products
GROUP BY booking_id
) bp ON b.id = bp.booking_id
INNER JOIN payment_methods p ON p.id = b.payment_method_id
WHERE b.status = ?
AND b.booked_at BETWEEN ? AND ?
GROUP BY p.name
ORDER BY p.name
I have no clue how to transform/write above query using laravel's query builder/eloquent way
Try to group by payment_method_id from the bookings table:
->groupBy('bookings.payment_method_id')
these are my tables. first one is appusers table.
CREATE TABLE IF NOT EXISTS `appusers` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(50) NOT NULL,
`is_active` tinyint(2) NOT NULL DEFAULT '0',
`zip` varchar(20) NOT NULL,
`city` text NOT NULL,
`country` text NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ;
second table is stickeruses table.
CREATE TABLE IF NOT EXISTS `stickeruses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`sticker_id` int(11) NOT NULL,
`count` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;
Third table is Devices
CREATE TABLE IF NOT EXISTS `devices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`regid` varchar(300) NOT NULL,
`imei` varchar(50) NOT NULL,
`device_type` tinyint(2) NOT NULL,
`notification` tinyint(2) NOT NULL DEFAULT '1',
`is_active` tinyint(2) NOT NULL DEFAULT '0',
`activationcode` int(6) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=28 ;
I Want to find the Sum(stickeruses.count) and COUNT(devices.id) for all appusers.
Here is my query.
SELECT `Appuser`.`id`, `Appuser`.`email`, `Appuser`.`country`, `Appuser`.`created`,
`Appuser`.`is_active`, SUM(`Stickeruse`.`count`) AS total, COUNT(`Device`.`id`)
AS tdevice
FROM `stickerapp`.`appusers` AS `Appuser`
LEFT JOIN `stickerapp`.`stickeruses` AS `Stickeruse`
ON (`Stickeruse`.`user_id`=`Appuser`.`id`)
INNER JOIN `stickerapp`.`devices` AS `Device`
ON (`Device`.`user_id`=`Appuser`.`id`)
WHERE `Appuser`.`is_active` = 1
GROUP BY `Appuser`.`id`
LIMIT 10
When I am applying each join separately the results are right, but I want to combine both joins. And when I am doing it then results are wrong. please help.
When mixing JOIN and LEFT JOIN it is a good idea to use parentheses to make it clear what your intent is.
I don't know what you need, but these syntaxes might give you different results:
FROM a LEFT JOIN ( b JOIN c ON b..c.. ) bc ON a..bc..
FROM ( a LEFT JOIN b ON a..b.. ) ab JOIN c ON ab..c..
Also, you can rearrange them do FROM a JOIN c LEFT JOIN b (plus parentheses) or any of several other arrangements. Granted, some pairs rearrangements are equivalent.
Also, beware; aggregates (such as SUM()) get inflated values when JOINing. Think of it this way: first the JOINs get all appropriate combinations of rows from the tables, then the SUM adds them up. With that in mind, see if this works better:
SELECT a.`id`, a.`email`, a.`country`, a.`created`, a.`is_active`,
( SELECT SUM(`count`)
FROM stickerapp.stickeruses
WHERE user_id = a.id
) AS total,
( SELECT COUNT(*)
FROM stickerapp.devices
WHERE user_id = a.id
) AS tdevice
FROM stickerapp.`appusers` AS a
WHERE a.`is_active` = 1
GROUP BY a.`id`
LIMIT 10
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.
I have these 2 queries and i would like to join them into one but i am unsure of how to go about it.
Query 1:
$query = "SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_publisher."='".$pub_id."'
AND ".$db_fld_comics_active."='1' GROUP BY ".$db_fld_comics_arc;
Query 2:
$q2 = mysql_query('SELECT '.$db_fld_arcs_title.' FROM '.$db_tbl_arcs.'
WHERE '.$db_fld_arcs_id.'="'.$result[$db_fld_comics_arc].'"');
Comics Table:
CREATE TABLE IF NOT EXISTS `comics` (
`id` varchar(255) NOT NULL,
`arc` int(255) NOT NULL,
`title` varchar(255) NOT NULL,
`issue` decimal(5,1) DEFAULT NULL,
`price` decimal(10,2) NOT NULL,
`plot` longtext NOT NULL,
`publisher` int(255) NOT NULL,
`isbn` varchar(255) NOT NULL,
`published` date NOT NULL,
`cover` varchar(255) NOT NULL DEFAULT './images/nopic.jpg',
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`views` int(255) NOT NULL DEFAULT '0',
`active` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `arc` (`arc`,`title`,`issue`,`publisher`)
);
Arcs Table:
CREATE TABLE IF NOT EXISTS `arcs` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`plot` longtext NOT NULL,
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `title` (`title`)
);
What I need to do is get the Arcs Title from the arcs table for the respective comic arc.
You need to use INNER JOIN for that since I presume that records are present on both tables.
SELECT a.*, b.title
FROM comics a INNER JOIN arcs b
on a.id = b.id
WHERE a.Title = 'VALUEHERE'
displays all details from comics table and the title of the arc
as simple as (joining 2 queries in one, by selecting only the required field and using IN):
SELECT
'.$db_fld_arcs_title.'
FROM '.$db_tbl_arcs.'
WHERE '.$db_fld_arcs_id.' IN (
SELECT '.$db_fld_comics_arc.'
FROM '.$db_tbl_comics.'
WHERE '.$db_fld_comics_publisher.'='".$pub_id."'
AND '.$db_fld_comics_active.'='1' GROUP BY '.$db_fld_comics_arc.'
)
This is my table layout:
-- Table structure for table `areas`
CREATE TABLE IF NOT EXISTS `areas` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`country` varchar(20) NOT NULL,
`city` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- Table structure for table `matches`
CREATE TABLE IF NOT EXISTS `matches` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`view_id` bigint(20) unsigned NOT NULL,
`status` enum('h','n') NOT NULL,
`exp_date` date NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- Table structure for table `users`
CREATE TABLE IF NOT EXISTS `users` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`limit_age` varchar(5) NOT NULL DEFAULT '18:30',
`limit_gender` varchar(2) DEFAULT NULL,
`notifications` int(11) NOT NULL DEFAULT '0',
`name` varchar(30) NOT NULL,
`email` varchar(40) NOT NULL,
`image_big` varchar(120) NOT NULL,
`image_small` varchar(120) NOT NULL,
`crop_data` int(11) DEFAULT NULL,
`visible` tinyint(1) NOT NULL DEFAULT '0',
`age` int(11) DEFAULT NULL,
`registered_at` datetime NOT NULL,
`views` bigint(20) unsigned NOT NULL DEFAULT '0',
`hots` bigint(20) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
I will try to explain this better:
I have a given ID.
I would like to select one entry from users which is not the ID i have given
AND which user_id does not exist in matches
AND has visible = 1
AND where any country + city matches the given users country + city
Is this the correct way to do it (12 is an example of an given ID):
SELECT *
FROM users a
INNER JOIN areas ON areas.user_id = a.id
WHERE a.id NOT IN (SELECT user_id FROM matches)
AND NOT a.id = '12'
AND a.limit_age = '18:30'
AND a.visible = '1'
AND areas.country = 'sverige'
AND areas.city = 'gbg'
Sorry for the confusion :)
Ok, I'll make an attempt at this:
SELECT *
FROM users a
INNER JOIN areas ON areas.user_id = a.id
WHERE a.id NOT IN (SELECT user_id FROM matches)
AND a.visible = '1'
AND a.limit_age = '18:30'
AND a.limit_gender = 'f'
AND areas.country = ?
AND areas.city = ?;
This is SELECTing from "users", and returning a result only if that user also has an entry in the "areas" table. The first item in the WHERE clause ensures that a row will not be returned if the users.id (a.id) is found in the user_id field on the "matches" table. Next, I added checks for visible = 1, limit_age, and limit_gender as specified in his attempt. Finally, I left country and city parameterized so that they can be added as parameters in the php code. If anything that should give you a starting point.