How to Show a Table data with Alphabetical Table in Php mySql? - php

I have a dictionary database with 950 rows of data. I would like to show the words list in alphabetical order in alphabetical table wise.
For an example table a shows first (5) words of data's starts from A:
A
-------------
Abacus
Abelian group
Abscissa
Absolute Value
Abstract Number
B
---------------
Bar Graph
Base
Base Depth of the Triangular Prism
Base of the Triangular Prism
Basic arithmetic operations
.
.
.
Z
---------------
Z-Intercept
Zero
Zero Divisors
Zero Element
Zone
every 5 data's fetch table should stop the current letter and jump to next letter.
I don't know how to do this.
My Table structure is
-------------------------
Name | Type
-------------------------
Id | int(3)
Word | varchar(45)
-------------------------

You should extract first letter with left
select left(word, 1) from table;
function and use huge union all query. details is described with examples in here.

I tried below query which has limit for now of 3.
In short what we have to do is - group by sorted words and limit to n
Created table as word_table
CREATE TABLE `offers`.`word_table` ( `Id` INT(3) NOT NULL , `Word`
VARCHAR(45) NOT NULL ) ENGINE = InnoDB;
Inserted your record in table
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('1', 'Abacus');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('2', 'Abelian group');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('3', 'Abscissa');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('4', 'Absolute Value');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('5', 'Abstract Number');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('6', 'Bar Graph');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('7', 'Base');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('8', 'Base Depth of the Triangular Prism');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('9', 'Base of the Triangular Prism');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('10', 'Basic arithmetic operations');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('11', 'Z-Intercept');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('12', 'Zero');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('13', 'Zero Divisors');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('14', 'Zero Element');
INSERT INTO `word_table` (`Id`, `Word`) VALUES ('15', 'Zone');
Query written for required output
SELECT x.*
FROM (SELECT t.*,
CASE
WHEN #category != substring(t.Word,1,1) THEN #rownum := 1
ELSE #rownum := #rownum + 1
END AS rank,
#category := substring(t.Word,1,1) AS var_category
FROM word_table t
JOIN (SELECT #rownum := NULL, #category := '') r
ORDER BY t.Word) x
WHERE x.rank <= 3
ORDER BY `x`.`var_category` ASC
OUTPUT
Hope this helps you!!!

You can use a single query to get the result of both the distinct first character and all the records with that letter as starting letter by using this
SELECT lower(left(filed_name,1)) as letter, group_concat(filed_name) as all_records FROM `table_name` where lower(left(filed_name,1)) in(SELECT DISTINCT LEFT(filed_name, 1) FROM table_name order by filed_name) group by lower(left(filed_name,1)) ORDER BY filed_name ASC

Related

Why am i getting incorrect count of another table records while using Group by and Left Join

Here is my Schema for tables :
CREATE TABLE users (`id` int, `name` varchar(50));
INSERT INTO users (`id`, `name`) VALUES (1, 'Test 1'), (2, 'Test 2'), (3, 'Test 3');
CREATE TABLE recipes (`id` int, `user_id` int , `name` varchar(100));
INSERT INTO recipes (`id`, `user_id`, `name`) VALUES
(null, 1, 'Receipe 1');
I need individual user receipe count, for that i've joined my user table with receipes, please look at below query
SELECT `User`.`id`, count('recipes.id') as recipes_cnt FROM `users` AS `User`
LEFT JOIN `recipes` AS `Recipe` ON (`User`.`id` = `Recipe`.`user_id`)
GROUP BY `User`.`id`
But it's giving count as 1 even if there are no receipes for user (normally it should be zero).
Here is mysql fiddle
Why am i getting results like this ?
please help me
Thanks in advance
I modified your SQL. replace count('recipes.id') to count(Recipe.id). These result gives ZERO's.
SELECT `User`.`id`, count(`Recipe`.id) as recipes_cnt FROM `users` AS `User`
LEFT JOIN `recipes` AS `Recipe` ON (`User`.`id` = `Recipe`.`user_id`)
GROUP BY `User`.`id`
Thank you.
There's a slight typo in your count:
count('recipes.id')
This is counting the string "recipes.id".
You need to count by the actual column:
count(Recipe.id)

PHP / MySQL query

After days of failing I hope that someone more skilled can help me with a solution.
I have two tables, one containing stocks and the other stock values. Please, you do not have to comment on field types etc as this is not a production development, I am only trying to get a grasp on join and mysql alias.
-- Stocks table:
DROP TABLE IF EXISTS `stocks`;
CREATE TABLE `stocks` (
`stock_id` int(11) NOT NULL AUTO_INCREMENT,
`stock_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`stock_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- Sample records:
INSERT INTO `stocks` VALUES ('1', 'HighTech');
INSERT INTO `stocks` VALUES ('2', 'NanoTech');
INSERT INTO `stocks` VALUES ('3', 'DotCom');
INSERT INTO `stocks` VALUES ('4', 'NewBiz');
-- Values table:
DROP TABLE IF EXISTS `vals`;
CREATE TABLE `values` (
`vals_id` int(11) NOT NULL AUTO_INCREMENT,
`stock_id` varchar(255) DEFAULT NULL,
`stock_value` int(11) DEFAULT NULL,
PRIMARY KEY (`vals_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- Sample records:
INSERT INTO `vals` VALUES ('1', '1', '50');
INSERT INTO `vals` VALUES ('2', '1', '700');
INSERT INTO `vals` VALUES ('3', '1', '540');
INSERT INTO `vals` VALUES ('4', '3', '15');
INSERT INTO `vals` VALUES ('5', '3', '44');
INSERT INTO `vals` VALUES ('6', '1', '60');
INSERT INTO `vals` VALUES ('7', '2', '10');
INSERT INTO `vals` VALUES ('8', '3', '53');
There could be 100s of stocks and 1000s of value records.
What I want to do is to print each stock together with a single (latest) stock value.
For stock number 3 I want to echo "DotCom" and the latest value "53", none of the others values.
Oh yeah , your table name values creating problem here , try to change it to someother name like vals or something.it would works/
here it is
SELECT * FROM stocks S JOIN vals V ON V.vals_id = ( SELECT MAX(vals_id) FROM vals Va WHERE Va.stock_id = S.stock_id )

#1062 - Duplicate entry '31' for key 'PRIMARY'

php error:
#1062 - Duplicate entry '31' for key 'PRIMARY'
query:
INSERT INTO `calls`(
`id`, `number`, `type`, `charges`, `duration`, `date`, `c_number`
)
VALUES (31,'03227453033','onnet',2,1,'2012-12-06','03216196069')
id is my primary key and its auto incremented. Currently there are 30 rows in my database
table.
For an auto-increment field, you leave it out of a SQL insert query as mysql will auto-populate it. Only do this if it is defined as an auto-increment field.
INSERT INTO `calls`(`number`, `type`, `charges`, `duration`, `date`, `c_number`)
VALUES ('03227453033' ,'onnet', 2, 1, '2012-12-06', '03216196069')
INSERT INTO calls(number, type, charges, duration, date, c_number) VALUES ('03227453033','onnet',2,1,'2012-12-06','03216196069')
This should work.
If id is auto incremented, then you shouldn't normally include it in your INSERT statement. It seems that you already have a row with id 31.

Pull records from orders table for the current week

I have a table with the following info...
Id | orderNumber | orderDate | customerId
orderDate is a MySQL datetime field and the current day, month, year and time is inserted into the database at the time the record is written.
So my question is how would I pull a list of orders for a certain day of this current week. My goal is to use the google charts API to make a chart for "This Week's Sales" that says something like:
var data = google.visualization.arrayToDataTable([
['Day', 'Sales'],
['Mon', 1],
['Tue', 0],
['Wed', 4],
['Thurs', 3],
['Fri', 0],
]);
Let's do exactly what you want:
SELECT
WEEKDAY(`datetime_field`) AS `week_day`,
COUNT(*) AS `sale_count`
FROM `orders`
WHERE YEARWEEK(`datetime_field`) = YEARWEEK(NOW())
GROUP BY `week_day`
ORDER BY `week_day` ASC;
This returns a set of records with week_day and sale_count. Learn more here. Use NOW() if you use local datetime or use UTC_TIMESTAMP() if you play by GMT.
Do keep in mind I don't know your database name or the fields' names. You need to fill those in.
WORKING EXAMPLE:
CREATE TABLE `orders` (
`OrderID` int(11) NOT NULL AUTO_INCREMENT,
`OrderDate` datetime NOT NULL,
`OrderValue` decimal(7,2) unsigned NOT NULL,
PRIMARY KEY (`OrderID`)
);
INSERT INTO `orders` VALUES ('1', '2012-10-29 14:02:19', '100.00');
INSERT INTO `orders` VALUES ('2', '2012-10-30 14:02:19', '123.00');
INSERT INTO `orders` VALUES ('3', '2012-10-31 14:02:19', '103.00');
INSERT INTO `orders` VALUES ('4', '2012-11-01 14:02:19', '232.00');
INSERT INTO `orders` VALUES ('5', '2012-11-02 14:02:19', '321.00');
INSERT INTO `orders` VALUES ('6', '2012-11-03 14:02:19', '154.00');
INSERT INTO `orders` VALUES ('7', '2012-11-04 14:02:19', '112.00');
INSERT INTO `orders` VALUES ('8', '2012-10-29 14:02:19', '100.00');
SELECT
WEEKDAY(`OrderDate`) AS `week_day`,
COUNT(*) AS `sales_count`,
SUM(`OrderValue`) AS `sales_value`
FROM `orders`
WHERE YEARWEEK(`OrderDate`) = YEARWEEK(NOW())
GROUP BY `week_day`
ORDER BY `week_day` ASC;
This is SQL to create a table, add 1 order per day for this week but 2 on Monday. And the query to fetch the report.
AND HERE'S SQLFIDDLE.COM SAMPLE.

Remove same values rows over different column mysql

I 'm stuck on a very basic problem, I want to skip the row which has duplicate values over three columns.
Table feeds
id,type,user_id,friend_id,date
1, 'friend', 4 , 5 , 5/5/2010
2, 'friend', 5 , 4 , 5/5/2010
Now this is how the data is saved (I can't change the saving module)
since both have same thing, so I want to pick them only as a 1 row not 2.
I don't want to validate and remove it at PHP end, b/c if I'll do at PHP the pagination would be disturb
Edit:
Table Structure
create table `feed` (
`id` double ,
`type` blob ,
`user_id` double ,
`type_id` double ,
`date` datetime
);
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('78','friends','1314','1313','2012-09-03 19:48:14');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('79','friends','1313','1314','2012-09-03 19:48:14');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('80','friends','1314','1312','2012-09-03 19:49:07');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('82','friends','1313','1312','2012-09-03 19:49:09');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('84','friends','1315','1312','2012-09-03 19:49:24');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('86','friends','1315','1313','2012-09-03 19:49:33');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('87','friends','1313','1315','2012-09-03 19:49:33');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('97','friends','1317','1312','2012-09-03 19:55:06');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('99','friends','1313','1317','2012-09-03 19:56:01');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('100','friends','1317','1313','2012-09-03 19:56:01');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('101','friends','1315','1317','2012-09-03 19:56:58');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('102','friends','1317','1315','2012-09-03 19:56:58');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('104','following','1313','1193','2012-09-03 19:59:39');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('105','following','1313','1308','2012-09-03 19:59:51');
insert into `feed` (`id`, `type`, `user_id`, `type_id`, `date`) values('106','following','1313','1098','2012-09-03 19:59:58');
And here is the ultimate solution! If the same friendship pair (reversed) exists it only takes the one where user_id>friend_id.
SELECT DISTINCT type, user_id, friend_id, date
FROM table t1
WHERE t1.user_id > t1.friend_id
OR NOT EXISTS (
SELECT * FROM table t2
WHERE t1.type=t2.type AND t1.date=t2.date
AND t2.user_id = t1.friend_id AND t2.friend_id = t1.user_id
)
The function you are looking for is DISTINCT(). That allows you to group the table by that column and remove duplicates.
Just make sure in your select statement that you also select the other field columns as well:
SELECT id, DISTINCT(type), user_id, friend_id, date FROM TABLENAME
You could perform a JOIN on the table itself, which should do what you are looking for.
Something like this might do the trick:
SELECT * FROM tableName a
JOIN tableName b ON a.user_id = b.friend_id
You should get rid of those duplicate records by running:
DELETE FROM table t1 WHERE
EXISTS (
SELECT * FROM table t2
WHERE t1.type=t2.type AND t1.date=t2.date
AND t2.user_id = t1.friend_id AND t2.friend_id = t1.user_id
AND t1.user_id > t2.user_id
)
Then you can get distinct friendship records with:
SELECT DISTINCT type, user_id, friend_id, date FROM table
Also, you can write a DB trigger that fires on INSERT, that checks if a duplicate (with reversed user_id and friend_id) already exists. If exists it does ROLLBACK, else allow INSERT.

Categories