How to get unread notifications (2 tables with FK) - php

I have 2 tables on my DB: user_notification and user_notification_read. It's a user notification system, the notifications are on user_notification and when a user reads a notification, it stores on user_notification_read with the notification id and the user id.
CREATE TABLE `user_notification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`related_user_id` int(11) NOT NULL,
`text` text NOT NULL,
`link` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `user_notification_read` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`notification_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `notification_id` (`notification_id`),
CONSTRAINT `user_notification_read_ibfk_1` FOREIGN KEY (`notification_id`) REFERENCES `user_notification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I want to make a SELECT to get the number of unread notifications for a certain user (by the user id).
I thought about using a
JOIN/WHERE (notification.id = user_notification_read.notification_id and user_notification.user_id = X)to get the rows from user_notification_read with a CASE to check if the row exists. If it doesn't exists, +1 on unread notifications.
I don't know if that's the appropriate logic to achieve it and don't know the syntax as well. I tried some google, but the examples are more complex than my case, which I believe it's simple.
How can I do that?
Fiddle: http://sqlfiddle.com/#!9/84a5ed/5/0
On the fiddle example, the count for unread notifications would be 2 for the user 1.

You should use a left join.
SELECT sum(r.notification_id is null)
FROM user_notification n
LEFT JOIN user_notification_read r ON r.notification_id = n.id
WHERE n.user_id = 1
r.notification_id is null means a notification wasn't read.

Related

MySQL query with large data performance

I'm a bit new to MySQL and I would like to know if I'm going right with these tables and query:
tb_anuncio
CREATE TABLE `tb_anuncio` (
`anuncio_id` int(11) NOT NULL auto_increment,
`anuncio_titulo` varchar(120) NOT NULL,
`anuncio_valor` decimal(10,2) NOT NULL,
`anuncio_valorTipo` int(11) default NULL,
`anuncio_telefone` varchar(20) NOT NULL,
`anuncio_descricao` text,
`anuncio_criado` timestamp NOT NULL default CURRENT_TIMESTAMP,
`bairro_id` int(11) NOT NULL,
`anuncio_status` int(11) default '0',
PRIMARY KEY (`anuncio_id`),
KEY `ta001_ix` (`bairro_id`)
) ENGINE=InnoDB DEFAULT charset utf8;
ALTER TABLE `tb_anuncio`
ADD CONSTRAINT `ta001_ix` FOREIGN KEY (`bairro_id`) REFERENCES `tb_bairro` (`bairro_id`) ON DELETE CASCADE ON UPDATE CASCADE;
tb_estado
CREATE TABLE `tb_estado` (
`estado_id` int(11) NOT NULL auto_increment,
`estado_nome` varchar(2) NOT NULL,
`estado_criado` timestamp NOT NULL default CURRENT_TIMESTAMP,
`estado_url` varchar(2) NOT NULL,
PRIMARY KEY (`estado_id`),
UNIQUE KEY `estado_url` (`estado_url`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
tb_cidade
CREATE TABLE `tb_cidade` (
`cidade_id` int(11) NOT NULL auto_increment,
`cidade_nome` varchar(100) NOT NULL,
`cidade_criado` timestamp NOT NULL default CURRENT_TIMESTAMP,
`estado_id` int(11) NOT NULL,
`cidade_url` varchar(150) NOT NULL,
PRIMARY KEY (`cidade_id`),
UNIQUE KEY `cidade_url` (`cidade_url`),
KEY `tc001_ix` (`estado_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `tb_cidade`
ADD CONSTRAINT `tc001_ix` FOREIGN KEY (`estado_id`) REFERENCES `tb_estado` (`estado_id`) ON DELETE CASCADE ON UPDATE CASCADE;
tb_bairro
CREATE TABLE `tb_bairro` (
`bairro_id` int(11) NOT NULL auto_increment,
`bairro_nome` varchar(100) NOT NULL,
`bairro_criado` timestamp NOT NULL default CURRENT_TIMESTAMP,
`cidade_id` int(11) NOT NULL,
`bairro_url` varchar(150) NOT NULL,
PRIMARY KEY (`bairro_id`),
UNIQUE KEY `bairro_url` (`bairro_url`),
KEY `tb001_ix` (`cidade_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `tb_bairro`
ADD CONSTRAINT `tb001_ix` FOREIGN KEY (`cidade_id`) REFERENCES `tb_cidade` (`cidade_id`) ON DELETE CASCADE ON UPDATE CASCADE;
Well I'm doing a query to show ads of a city/state, my query looks like:
Query
select a.anuncio_id,a.anuncio_titulo,a.anuncio_valor,a.anuncio_valorTipo,a.anuncio_descricao
from tb_anuncio a inner join(
tb_bairro b inner join(
tb_cidade c inner join
tb_estado d on d.estado_id=c.estado_id) on c.cidade_id=b.cidade_id) on b.bairro_id=a.bairro_id
where a.anuncio_status=1 and d.estado_id=:estado_id and c.cidade_id=:cidade_id and b.bairro_id=:bairro_id
group by a.anuncio_id
order by a.anuncio_id desc
limit :limit
I would like to know if I'm going right and it will work well when these tables get about 5k-10k of records.
I'm using PHP PDO MySQL.
Thanks.
Although it doesn't affect performance, the typical way to write a query would not have parentheses in the FROM clause. Also, I doubt the group by is necessary:
select a.*
from tb_anuncio a inner join
tb_bairro b
on b.bairro_id = a.bairro_id inner join
tb_cidade c
on c.cidade_id = b.cidade_id inner join
tb_estado e
on e.estado_id = c.estado_id
where a.anuncio_status = 1 and e.estado_id = :estado_id and
c.cidade_id = :cidade_id and b.bairro_id = :bairro_id
order by a.anuncio_id desc
limit :limit;
You can simplify this, because you do not need all the joins -- the join keys are in referencing tables:
select a.*
from tb_anuncio a inner join
tb_bairro b
on b.bairro_id = a.bairro_id inner join
tb_cidade c
on c.cidade_id = b.cidade_id
where a.anuncio_status = 1 and c.estado_id = :estado_id and
c.cidade_id = :cidade_id and b.bairro_id = :bairro_id
order by a.anuncio_id desc
limit :limit;
I don't know Portuguese, but seems like one estado contains many cidades, which contains many bairros. If this is correct, then the schema is wrong. Fixing the schema will lead to improving the performance.
There should be one bairro in the query, not three such items in the WHERE.
Furthermore, it is usually more practical for tb_bairro to include information about the cidade and estado, not tb_anuncio.
Once you have done those things, the GROUP BY can probably be eliminated, thereby adding more performance.
And add
INDEX(anuncio_status, bairro_id, anuncio_id)

Optimizing queries on larger MySQL database

I'm coding a website which will store some offers (ex. job offers). In the end, it could contain more than 1M offers. Now I have problems with some inefficient SQL queries.
Scenario:
Each offer can be assigned into category (ex. IT jobs)
Each category has custom fields (ex. IT jobs can have custom field of type "price" which will represent text box accepting number (price) - in our example, let's say we have price input of expected salary)
Each offer stores meta data with values of these category custom fields
DB fields which will be used for filtering have indexes
Table category (I'm using nested sets to store categories hierarchy):
CREATE TABLE `category` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
`lft` int(11) DEFAULT NULL,
`rgt` int(11) DEFAULT NULL,
`depth` int(11) DEFAULT NULL,
`order` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `category_parent_id_index` (`parent_id`),
KEY `category_lft_index` (`lft`),
KEY `category_rgt_index` (`rgt`)
) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Table category_field:
CREATE TABLE `category_field` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`category_id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`optional` tinyint(1) NOT NULL DEFAULT '0',
`type` enum('price','number','date','color') COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `category_field_category_id_index` (`category_id`),
CONSTRAINT `category_field_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Table offer:
CREATE TABLE `offer` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`text` text COLLATE utf8_unicode_ci NOT NULL,
`category_id` int(10) unsigned NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `offer_category_id_index` (`category_id`),
CONSTRAINT `offer_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Table offer_meta:
CREATE TABLE `offer_meta` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`offer_id` int(10) unsigned NOT NULL,
`category_field_id` int(10) unsigned NOT NULL,
`price` double NOT NULL,
`number` int(11) NOT NULL,
`date` date NOT NULL,
`color` varchar(7) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `offer_meta_offer_id_index` (`offer_id`),
KEY `offer_meta_category_field_id_index` (`category_field_id`),
KEY `offer_meta_price_index` (`price`),
KEY `offer_meta_number_index` (`number`),
KEY `offer_meta_date_index` (`date`),
KEY `offer_meta_color_index` (`color`),
CONSTRAINT `offer_meta_category_field_id_foreign` FOREIGN KEY (`category_field_id`) REFERENCES `category_field` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `offer_meta_offer_id_foreign` FOREIGN KEY (`offer_id`) REFERENCES `offer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=107769 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
When I set up some filters on my page (for example, for our salary custom field) I have to start with query which returns MIN and MAX prices in available offer_meta records (I want to show a range slider to user in front-end, so I need MIN/MAX values for this range):
select MIN(`price`) AS min, MAX(`price`) AS max from `offer_meta` where `category_field_id` = ? limit 1
I found out that these queries are most inefficient from all queries I'm making (above query takes over 500ms when offer_meta table has few thousand of records).
Other inefficient queries (offer_meta has 107k records):
Obtaining MIN and MAX values for slider to filter numbers
select MIN(`number`) AS min, MAX(`number`) AS max from `offer_meta` where `category_field_id` = ? limit 1
Obtaining MIN and MAX prices for slider to filter by prices
select MIN(`price`) AS min, MAX(`price`) AS max from `offer_meta` where `category_field_id` = ? limit 1
Obtaining MIN and MAX date for date range restrictions
select MIN(`date`) AS min, MAX(`date`) AS max from `offer_meta` where `category_field_id` = ? limit 1
Obtaining colors with counts to show list of colors with numbers
select `color`, count(*) as `count` from `offer_meta` where `category_field_id` = ? group by `color`
Example of full query to get offers count with multiple filter criteria (0.5 sec)
select count(*) as count from `offer` where id in (select
distinct offer_id
from offer_meta om
where offer_id in (select
distinct offer_id
from offer_meta om
where offer_id in (select
distinct offer_id
from offer_meta om
where offer_id in (select
distinct om.offer_id
from offer_meta om
join category_field cf on om.category_field_id = cf.id
where
cf.category_id in (2,3,4,41,43,5,6,7,8,37) and
om.category_field_id = 1 and
om.number >= 1 and
om.number <= 50) and
om.category_field_id = 2 and
om.price >= 2 and
om.price <= 4545) and
om.category_field_id = 3 and
om.date >= '0000-00-00' and
om.date <= '2015-04-09') and
category_field_id = 4 and
om.color in ('#0000ff'))
The same query without aggregation function (COUNT) is few times faster (just to get IDs).
Question:
Is it possible to tweak those queries, or do you have any suggestion on how to implement my logic (offers with categories and custom fields dynamically added in admin to each category) with different table schema? I tried few more schemes, but no success.
Question 2:
Do you think this is my MySQL server problem and if I buy VPS, it will be okay?
Help to understand even better:
I was strongly inspired by WordPress schema for custom fields, so the logic is similar.
Last notes:
Also, I'm working on Laravel framework and I'm using Eloquent ORM.
Sorry for my english, I hope I made my problem clear :-)
Thank you in advance,
Patrik
It is not a MySql problem. in your scenario we found huge data collection. naturally relational databases are not efficient for some queries.(i faced a situation with oracle)
the practice for win this kind of situations is using graph databases.
it seems it is hard with the situation you are facing at the movement.
I heard that the Lucene has some kind of support for indexing large databases for selecting purpose. i dont know how exactly do it.
http://en.wikipedia.org/wiki/Lucene

MySql Properly Join Complex Data/Tables

Abstract:
Every client is given a specific xml ad feed (publisher_feed table). Everytime there is a query or a click on that feed, it gets recorded (publisher_stats_raw table) (Each query/click will have multiple rows depending on the subid passed by the client (We can sum the clicks together)). The next day, we pull stats from an API to grab the previous days revenue numbers (rev_stats table) (Each revenue stat might have multiple rows depending on the country of the click (We can sum the revenue together)). Been having a hard time trying to link together these three tables to find the average RPC for each client for the previous day.
Table Structure:
CREATE TABLE `publisher_feed` (
`publisher_feed_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`alias` varchar(45) DEFAULT NULL,
`user_id` int(10) unsigned DEFAULT NULL,
`remote_feed_id` int(10) unsigned DEFAULT NULL,
`subid` varchar(255) DEFAULT '',
`requirement` enum('tq','tier2','ron','cpv','tos1','tos2','tos3','pv1','pv2','pv3','ar','ht') DEFAULT NULL,
`status` enum('enabled','disabled') DEFAULT 'enabled',
`tq` decimal(4,2) DEFAULT '0.00',
`clicklimit` int(11) DEFAULT '0',
`prev_rpc` decimal(20,10) DEFAULT '0.0000000000',
PRIMARY KEY (`publisher_feed_id`),
UNIQUE KEY `alias_UNIQUE` (`alias`),
KEY `publisher_feed_idx` (`remote_feed_id`),
KEY `publisher_feed_user` (`user_id`),
CONSTRAINT `publisher_feed_feed` FOREIGN KEY (`remote_feed_id`) REFERENCES `remote_feed` (`remote_feed_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `publisher_feed_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=124 DEFAULT CHARSET=latin1$$
CREATE TABLE `publisher_stats_raw` (
`publisher_stats_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`unique_data` varchar(350) NOT NULL,
`publisher_feed_id` int(10) unsigned DEFAULT NULL,
`date` date DEFAULT NULL,
`subid` varchar(255) DEFAULT NULL,
`queries` int(10) unsigned DEFAULT '0',
`impressions` int(10) unsigned DEFAULT '0',
`clicks` int(10) unsigned DEFAULT '0',
`filtered` int(10) unsigned DEFAULT '0',
`revenue` decimal(20,10) unsigned DEFAULT '0.0000000000',
PRIMARY KEY (`publisher_stats_id`),
UNIQUE KEY `unique_data_UNIQUE` (`unique_data`),
KEY `publisher_stats_raw_remote_feed_idx` (`publisher_feed_id`)
) ENGINE=InnoDB AUTO_INCREMENT=472 DEFAULT CHARSET=latin1$$
CREATE TABLE `rev_stats` (
`rev_stats_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date` date DEFAULT NULL,
`remote_feed_id` int(10) unsigned DEFAULT NULL,
`typetag` varchar(255) DEFAULT NULL,
`subid` varchar(255) DEFAULT NULL,
`country` varchar(2) DEFAULT NULL,
`revenue` decimal(20,10) DEFAULT NULL,
`tq` decimal(4,2) DEFAULT NULL,
`finalized` int(11) DEFAULT '0',
PRIMARY KEY (`rev_stats_id`),
KEY `rev_stats_remote_feed_idx` (`remote_feed_id`),
CONSTRAINT `rev_stats_remote_feed` FOREIGN KEY (`remote_feed_id`) REFERENCES `remote_feed` (`remote_feed_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=58 DEFAULT CHARSET=latin1$$
Context:
Each remote_feed has a specific subid/typetag given to it. So we need to match up the both the remote_feed_id and the subid columsn from the publisher_feed table to the remote_feed_id and typetag columns in the revenue stats table.
My current, non working, implementation:
SELECT
pf.publisher_feed_id, psr.date, sum(clicks), sum(rs.revenue)
FROM
xml_network.publisher_feed pf
JOIN
xml_network.publisher_stats_raw psr
ON
psr.publisher_feed_id = pf.publisher_feed_id
JOIN
xml_network.rev_stats rs
ON
rs.remote_feed_id = pf.remote_feed_id
WHERE
pf.requirement = 'tq'
AND
pf.subid = rs.typetag
AND
psr.date <> date(curdate())
GROUP BY
psr.date
ORDER BY
psr.date DESC
LIMIT 1;
The above keeps pulling the wrong data out of the rev_stats table (pulls the sum of the correct stats, but repeats it over because of a join). Any help with how I would be able to properly pull the correct data would be greatly helpful ( I could use multiple queries and PHP to get the correct results, but what's the fun in that!)
Figured out a way to get this accomplished. Its def not a fast method by any means, needing 4 selects to get it done, but it works flawlessly =)
SELECT
pf.publisher_feed_id,
round(
(
SELECT
SUM(rs.revenue)
FROM
xml_network.rev_stats rs
WHERE
rs.remote_feed_id = pf.remote_feed_id
AND
rs.typetag = pf.subid
AND
rs.date = subdate(current_date, 1)
),10)as revenue,
(
SELECT
MAX(rs.tq)
FROM
xml_network.rev_stats rs
WHERE
rs.remote_feed_id = pf.remote_feed_id
AND
rs.typetag = pf.subid
AND
rs.date = subdate(current_date, 1)
) as tq,
(
SELECT
SUM(psr.clicks)-SUM(psr.filtered)
FROM
xml_network.publisher_stats_raw psr
WHERE
psr.publisher_feed_id = pf.publisher_feed_id
AND
psr.date = subdate(current_date, 1)
) as clicks
FROM
xml_network.publisher_feed pf
WHERE
pf.requirement = 'tq';

Optimizing sql statements to reduce MySQL server load

$sql1 = "SELECT questions FROM last_check_date WHERE user_id=? ORDER BY questions DESC LIMIT 1";
$sql2 = "SELECT id FROM questions WHERE add_dt>?";
What do statements above do?
When I execute sql1, it gets last check date for user.
Then I'm executing second query, to fetch all id's where add date>last check date (from sql1) and return affected rows count.
What I want to do is to merge this 2 statements into 1, and optimize query count. Following problem may occur:
There is no row for user in $sql1: must select all rows in sql2 and return affected rows count.
I can't figure out how it must look like.. Thx in advance
UPDATE
SHOW CREATE TABLE last_check_date; result is
CREATE TABLE `last_check_date` (
`id` int(11) unsigned NOT NULL,
`user_id` bigint(20) unsigned NOT NULL,
`questions` datetime DEFAULT NULL,
`users` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And SHOW CREATE TABLE questions;
CREATE TABLE `questions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`author_id` bigint(20) unsigned DEFAULT NULL,
`question` text NOT NULL,
`var_a` text NOT NULL,
`var_b` text NOT NULL,
`var_c` text NOT NULL,
`var_d` text NOT NULL,
`var_e` text NOT NULL,
`subject` int(11) unsigned DEFAULT NULL,
`chapter` int(11) unsigned DEFAULT NULL,
`section` int(11) unsigned DEFAULT NULL,
`paragraph` int(11) unsigned DEFAULT NULL,
`rank` tinyint(2) NOT NULL,
`add_dt` datetime NOT NULL,
`answer` varchar(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_chapters-id` (`chapter`),
KEY `fk_paragraphs-id` (`paragraph`),
KEY `fk_subjects-id` (`subject`),
KEY `fk_sections-id` (`section`),
KEY `fk_author-id` (`author_id`),
CONSTRAINT `fk_author-id` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_chapters-id` FOREIGN KEY (`chapter`) REFERENCES `chapters` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_paragraphs-id` FOREIGN KEY (`paragraph`) REFERENCES `paragraphs` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_sections-id` FOREIGN KEY (`section`) REFERENCES `sections` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_subjects-id` FOREIGN KEY (`subject`) REFERENCES `subjects` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
$sql = "
SELECT q.id
FROM questions q
LEFT JOIN (
SELECT questions
FROM last_check_date
WHERE user_id=?
ORDER BY questions
DESC LIMIT 1
) l ON q.add_dt > l.questions"
$rs = mysql_query($sql);
$rowcount = mysql_num_rows($rs);
I don't know yet the proper syntax for PDO/MYSQLI, please adapt to your prefered driver.
See below. I have assumed that if there are no records in last_check_date that you still want to show questions (in that case all of them).
select q.id
from questions q
left outer join (
select max(questions) as questions
from last_check_date
where user_id = ?
) lcd on q.add_date > lcd.questions
where user_id = ?
order by questions desc

SQL error when generated SQL command with Doctrine PHP

I use Doctrine on my PHP web application with a MySQL database. I have a little problem with my request :
$q = Doctrine_Query::create()
->select('event.EventDate, event.EventId, player.PlayerId, player.FirstName,
player.LastName, player.Login, player.Email,
event_period.EventPeriodId, event.Type, event.Description,
period.StartHour, period.EndHour, player_event_period.Participate,
event_period.CourtNumber')
->from('Event event, Player player, Period period')
->leftJoin('player.PlayerEventPeriod player_event_period')
->leftJoin('player_event_period.EventPeriod event_period')
->where('period.PeriodId = event_period.PeriodId')
->andWhere('event.EventId = event_period.EventId');
if I show what is the generated MySQL command, I can see
SELECT e.eventid AS e__eventid, e.eventdate AS e__eventdate, e.type AS e__type, e.description AS e__description, p.playerid AS p__playerid, p.firstname AS p__firstname, p.lastname AS p__lastname, p.login AS p__login, p.email AS p__email, p2.periodid AS p2__periodid, p2.starthour AS p2__starthour, p2.endhour AS p2__endhour, p3.playereventperiodid AS p3__playereventperiodid, p3.participate AS p3__participate, e2.eventperiodid AS e2__eventperiodid, e2.courtnumber AS e2__courtnumber
FROM event e, player p, period p2
LEFT JOIN player_event_period p3 ON p.playerid = p3.playerid
LEFT JOIN event_period e2 ON p3.eventperiodid = e2.eventperiodid
WHERE (
p2.periodid = e2.periodid
AND e.eventid = e2.eventid
);
I get error :
#1054 - Unknown column 'p.playerid' in 'on clause'
What's wrong with my request ?
Thank you in advance
EDIT:
If that could help you. I have add the script that creates my database tables.
CREATE TABLE `event` (
`EventId` int(11) NOT NULL AUTO_INCREMENT,
`Type` varchar(100) NOT NULL,
`Description` text,
`EventDate` datetime NOT NULL,
`CreationDate` datetime NOT NULL,
`UpdateDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`EventId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `event_period` (
`EventPeriodId` int(11) NOT NULL AUTO_INCREMENT,
`PeriodId` int(11) NOT NULL,
`EventId` int(11) NOT NULL,
`CourtNumber` int(11) NOT NULL,
`CreationDate` datetime NOT NULL,
`UpdateDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`EventPeriodId`),
KEY `fk_event_period_to_period` (`PeriodId`),
KEY `fk_event_period_to_event` (`EventId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `period` (
`PeriodId` int(11) NOT NULL AUTO_INCREMENT,
`StartHour` time NOT NULL,
`EndHour` time NOT NULL,
`CreationDate` datetime NOT NULL,
`UpdateDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`PeriodId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `player` (
`PlayerId` int(11) NOT NULL AUTO_INCREMENT,
`Login` varchar(100) NOT NULL,
`Password` varchar(100) NOT NULL,
`RankId` int(11) NOT NULL DEFAULT '1',
`FirstName` varchar(100) NOT NULL,
`LastName` varchar(100) NOT NULL,
`Email` varchar(100) NOT NULL,
`ValidateId` varchar(100) NOT NULL,
`InscriptionDate` datetime NOT NULL,
`Enable` tinyint(1) NOT NULL,
`CreationDate` datetime NOT NULL,
`UpdateDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`PlayerId`),
KEY `fk_player_to_rank` (`RankId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `player_event_period` (
`PlayerEventPeriodId` int(11) NOT NULL AUTO_INCREMENT,
`PlayerId` int(11) NOT NULL,
`EventPeriodId` int(11) NOT NULL,
`Participate` tinyint(1) NOT NULL,
`CreationDate` datetime NOT NULL,
`UpdateDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`PlayerEventPeriodId`),
KEY `fk_player_event_period_to_player` (`PlayerId`),
KEY `fk_player_event_period_to_event_period` (`EventPeriodId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `event_period`
ADD CONSTRAINT `fk_event_period_to_period` FOREIGN KEY (`PeriodId`) REFERENCES `period` (`PeriodId`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_event_period_to_event` FOREIGN KEY (`EventId`) REFERENCES `event` (`EventId`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `player`
ADD CONSTRAINT `fk_player_to_rank` FOREIGN KEY (`RankId`) REFERENCES `rank` (`RankId`);
ALTER TABLE `player_event_period`
ADD CONSTRAINT `fk_player_event_period_to_player` FOREIGN KEY (`PlayerId`) REFERENCES `player` (`PlayerId`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_player_event_period_to_event_period` FOREIGN KEY (`EventPeriodId`) REFERENCES `event_period` (`EventPeriodId`) ON DELETE CASCADE ON UPDATE CASCADE;
Not sure how your models look but do your table called "player" have a column called "playerid" in it?
That's what mysql is complaining about.
[Edit]
I think that Doctrine prefers column names i lowercase.
(Can't remember if MySQL is case-sensitive regarding column names...)
Case sensitivity of MySQL column names depends on how the database/schema/tables are configured, but it looks like yours are case sensitive.
You haven't provided the entity definitions so I'm guessing at the issue, but try setting the name of the column.
For example for player id the annotation would be:
/**
* #Column(name="PlayerId", type="integer", length=11, nullable=false)
* #Id
* GeneratedValue(strategy="AUTO")
*/
protected $PlayerId;

Categories