ALL,
I just tried following query:
SELECT cols.column_name, cols.data_type, cols.character_maximum_length, cols.character_octet_length,
cols.numeric_precision, cols.numeric_scale, cols.column_default, cols.is_nullable,
cols.ordinal_position, kcu.column_name
FROM information_schema.columns cols, information_schema.key_column_usage kcu
WHERE kcu.constraint_name = 'PRIMARY' AND kcu.table_schema = cols.table_schema AND
kcu.table_name = cols.table_name AND cols.table_schema = 'draft' AND cols.table_name = 'leagues';
The last column of that query does return the primary key column name.
However, what I'd like to see instead is this:
If the column is a primary key then the query will output '1' in the last query column.
If the column is not a primary key, then the query will output '0' in the last query column.
Is there a function inside mySQL that will help me do that?
Thank you.
Never use commas in the FROM clause. Always use proper, explicit JOIN syntax.
The "function" is case:
SELECT cols.column_name, cols.data_type, cols.character_maximum_length, cols.character_octet_length,
cols.numeric_precision, cols.numeric_scale, cols.column_default, cols.is_nullable,
cols.ordinal_position,
(CASE WHEN kcu.column_name IS NULL THEN 0 ELSE 1 END) as pk_flag
FROM information_schema.columns cols LEFT JOIN
information_schema.key_column_usage kcu
ON kcu.constraint_name = 'PRIMARY' AND kcu.table_schema = cols.table_schema AND
kcu.table_name = cols.table_name
WHERE cols.table_schema = 'draft' AND cols.table_name = 'leagues';
This is the query I will use:
SELECT cols.column_name, cols.data_type, cols.character_maximum_length, cols.character_octet_length,
cols.numeric_precision, cols.numeric_scale, cols.column_default, cols.is_nullable,
cols.ordinal_position,
(CASE WHEN kcu.column_name = cols.column_name THEN 1 ELSE 0 END) as pk_flag
FROM information_schema.columns cols, information_schema.key_column_usage kcu
WHERE kcu.constraint_name = 'PRIMARY' AND kcu.table_schema = cols.table_schema AND
kcu.table_name = cols.table_name AND cols.table_schema = 'draft' AND cols.table_name = 'leagues';
It works as expected in mySQL Workbench.
Note: This is not an answer to your question.
#Igor, here are my tests regarding running a select query using FROM on two tables (table1, resp. table2), compared with a select command called by LEFT JOIN-ing the same tables.
As you mentioned, there is indeed a difference: LEFT JOIN-ing implies the existence of one or more relations between the tables, but FROM-ing do not (in the context).
My question is, why would/should data from uncorrelated tables be fetched?
Table creation:
-- Create table1 table.
CREATE TABLE `tests`.`table1` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL,
PRIMARY KEY (`id`));
-- Create table2 table.
CREATE TABLE `tests`.`table2` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL,
PRIMARY KEY (`id`));
Value insertions:
-- Insert values into table1 table.
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('1', 'TAB1 1');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('2', 'TAB1 2');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('3', 'TAB1 3');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('4', 'TAB1 4');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('5', 'TAB1 5');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('6', 'TAB1 6');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('7', 'TAB1 7');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('8', 'TAB1 8');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('9', 'TAB1 9');
INSERT INTO `tests`.`table1` (`id`, `name`) VALUES ('10', 'TAB1 10');
-- Insert values into table2 table.
INSERT INTO `tests`.`table2` (`id`, `name`) VALUES ('1', 'TAB2 1');
INSERT INTO `tests`.`table2` (`id`, `name`) VALUES ('2', 'TAB2 2');
INSERT INTO `tests`.`table2` (`id`, `name`) VALUES ('3', 'TAB2 3');
Table previews:
FROM query & result:
JOIN query & result:
Related
BEGIN;
INSERT INTO `address` (`postal address`, `email`, `phone_number`) VALUES ('1527', 'tommydd#gmail.com', '0766452152');
INSERT INTO `bank` (`bank_number`, `bank_name`,`branch`) VALUES ('050002345678', 'Equity', 'Haniwa');
INSERT INTO `fees` (`perannum`, `fee_balance`) VALUES ('27000', '1500.34');
INSERT INTO `institution` (`Institution_name`, `course`, `form_study_year`, `adm_upi`, `type`) VALUES ('KU', 'Computer Science', '3rd Year', 'STT/B/01-003/2009', 'Public Day');
INSERT INTO `student` (`address_id`, `fees_id`, `bank_id`, `institution_id`, `first_name`, `middle_name`, `last_name`, `gender`, `date_of_birth`, `bc_no`, `parent`) VALUES ('LAST_INSERT_ID()', 'LAST_INSERT_ID()', 'LAST_INSERT_ID()', 'LAST_INSERT_ID()', 'Tommy', 'Gas', 'John', 'Male', '11/04/1999', '3868686', 'Both Alive');
COMMIT;
I want to get count of post subscribed by user below is my table schema , please help me with query for the same, i trie many option but could not do it
I tried and was able to get post count of user below is my query , but here i have used static user id , i want single query to list count for all users
SELECT COUNT(*)
FROM CATMAPPING INNER JOIN
POST ON CATMAPPING.pid = POST.id
where FIND_IN_SET(CATMAPPING.cid,(select selectedcatid from subscribers where id='1'));
Desire OP
Desired Output
uemail Postcount
-----------------------------
a#s.com 4
b#s.com 8
c#s.com 10
d#s.com 4
SQL fiddel link : http://sqlfiddle.com/#!9/4fff8f/2
CREATE TABLE subscribers (
`id` int(10),
`uemail` varchar(255) DEFAULT NULL,
`selectedcatid` varchar(255) DEFAULT NULL
) ;
ALTER TABLE subscribers ADD PRIMARY KEY (`id`);
ALTER TABLE subscribers MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT;
INSERT INTO subscribers (`uemail`, `selectedcatid`) VALUES ('a#s.com', '1'),
('b#s.com', '1,3'),
('c#s.com', '1,2,3'),
('d#s.com', '3');
CREATE TABLE POST (
`id` int(10),
`title` varchar(255) DEFAULT NULL
) ;
INSERT INTO POST (`id`, `title`) VALUES ('1', 'ABC'),
('2', 'DEF'),
('3', 'GHI'),
('4', 'JKL'),
('5', 'MNO'),
('6', 'PQR'),
('7', 'STU'),
('8', 'VXZ'),
('9', 'ASO'),
('10', 'LMO');
CREATE TABLE CATMAPPING (
`cid` int(10),
`pid` int(10) DEFAULT NULL
) ;
INSERT INTO CATMAPPING (`pid`, `cid`) VALUES ('1', '1'),
('2', '2'),
('3', '3'),
('4', '1'),
('5', '2'),
('6', '3'),
('7', '3'),
('8', '3'),
('9', '1'),
('10', '1');
Here is the correct query I wrote in sql server may be some syntax is diffrent but it gives me correct result I creates a table valued function and then used it for the query .
declare #tempsub as table (subid int,selectcatId int )
insert into #tempsub
select id ,string
from subscribers
CROSS APPLY [dbo].[ufn_CSVToTable] (selectedcatid)
--select * from #tempsub
-- subid is the id of the subscribes table
SELECT subid , count(*) from post p inner join CATMAPPING c on c.pid = p.id
left join #tempsub t on t.selectcatId= c.cid
group by t.subid
-- below is the code for tabled valued function it return a table for comma seprated string
create FUNCTION dbo.[ufn_CSVToTable] ( #StringInput VARCHAR(8000) )
RETURNS #OutputTable TABLE ( [String] nVARCHAR(1000) )
AS
BEGIN
DECLARE #String nVARCHAR(1000)
WHILE LEN(#StringInput) > 0
BEGIN
SET #String = LEFT(#StringInput,
ISNULL(NULLIF(CHARINDEX(',', #StringInput) - 1, -1),
LEN(#StringInput)))
SET #StringInput = SUBSTRING(#StringInput,
ISNULL(NULLIF(CHARINDEX(',', #StringInput), 0),
LEN(#StringInput)) + 1, LEN(#StringInput))
INSERT INTO #OutputTable ( [String] )
VALUES ( #String )
END
RETURN
END
I have two tables named as
product_Category
CREATE TABLE `product_category` (
`pid` int(11) NOT NULL,
`cid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `product_category`
--
/*!40000 ALTER TABLE `product_category` DISABLE KEYS */;
INSERT INTO `product_category` (`pid`,`cid`) VALUES
(1,1),
(2,3),
(3,2),
(4,2),
(5,3),
(1,2),
(2,4),
(3,1);
and category table
CREATE TABLE `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cat_name` varchar(50) NOT NULL,
`mapped_cat_id` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `category`
--
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` (`id`,`cat_name`,`mapped_cat_id`) VALUES
(1,'c1','1,2,4'),
(2,'c2','2,3'),
(3,'c3','3,4'),
(4,'c4','4,1,3');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
When I run this query
select distinct pid from
product_category where cid in (1,2,4)
I got result of pid (1,3,4,2)
but when I run query
select distinct pid from
product_category where cid in (select mapped_cat_id from category where id=1)
I got result of pid (1,3)
How to use subquery with 'IN' clause ?
I know my way of asking question is wrong because I dont know how to create table here thats why I wrote query instead of table.
i think coma separated values are not good.
Delete contents of your category table and use following query to insert
INSERT INTO `category` (`id`, `cat_name`, `mapped_cat_id`) VALUES
(1, 'c1', '1'),
(2, 'c2', '2'),
(3, 'c3', '3'),
(4, 'c4', '4'),
(5, 'c1', '2'),
(6, 'c1', '4'),
(7, 'c2', '3'),
(8, 'c3', '4'),
(9, 'c4', '1'),
(10, 'c4', '3');
Then use following query to get your result
select distinct pid from
product_category where cid in
(select mapped_cat_id from category where cat_name='c1')
You might be looking for FIND_IN_SET() function
select distinct pid from
product_category where FIND_IN_SET(cid,
(select mapped_cat_id from category where id=1));
SAMPLE FIDDLE
Since mapped_cat_id is saved as comma - seperated values(varchar), it is taking only first integer for the condition checking. Here it is 1
I wish to know which team in "TX" have not played a game. (In other words Im looking for a selection of records where there is no related record in the many table.)
Here is the SQL:
(Or if You prefer the sql fiddle is here:http://sqlfiddle.com/#!2/14106 )
CREATE TABLE `Team` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(45) NULL ,
`State` VARCHAR(45) NULL ,
PRIMARY KEY (`ID`) );
CREATE TABLE `Games` (
`ID` INT NOT NULL AUTO_INCREMENT,
`Team_ID` INT NULL ,
`Game_Day` DATE NULL ,
PRIMARY KEY (`ID`) );
INSERT INTO `Team` (`Name`, `State`) VALUES ('Rams', 'TX');
INSERT INTO `Team` (`Name`, `State`) VALUES ('Rockets', 'OK');
INSERT INTO `Team` (`Name`, `State`) VALUES ('Bombers', 'TX');
INSERT INTO `Team` (`Name`, `State`) VALUES ('Yellow Jackets', 'NV');
INSERT INTO `Team` (`Name`, `State`) VALUES ('Wildcats', 'CT');
INSERT INTO `Team` (`Name`, `State`) VALUES ('Miners', 'CO');
INSERT INTO `Team` (`Name`, `State`) VALUES ('Bolts', 'TX');
INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('2', '2013-03-16');
INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('2', '2013-01-01');
INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('3', '2013-04-16');
INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('5', '2013-02-02');
INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('4', '2013-02-12');
INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('6', '2013-01-09');
INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('6', '2013-01-01');
INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('3', '2013-05-01');
I should get the result:
ID Name
1 Rams
7 Bolts
SELECT `ID`, `Name` FROM `TEAM`
WHERE `ID` NOT IN (SELECT DISTINCT(`Team_ID`) from `Games`)
AND `State` = 'TX';
SqlFiddle here.
Use an outer join, selecting only those rows that don't match
SELECT t.*
FROM TEAM t
LEFT JOIN GAMES g ON g.team_id = t.id
WHERE t.state = 'TX'
AND g.team_id is null -- return only rows that *don't* join
This this running in SQL Fiddle
Note that using a join will out-perform a sub-query approach, especially when data sets become large.
You can also left-join to the Games table and filter for where there isn't a corresponding Games row. This is usually faster than NOT IN when the tables have a lot of rows:
SELECT Team.ID, Team.Name
FROM Team
LEFT JOIN Games ON Team.ID = Games.Team_ID
WHERE Team.State = 'TX' AND Games.ID IS NULL;
If there isn't a Games row to go with the Teams row, the Games.ID column will be null in the result, so if you filter on Games.ID IS NULL you'll get all the rows where a team has no games.
There's a SQL Fiddle here.
Hope this would help.
select t.ID,t.NAME
FROM Team t
WHERE t.state = 'TX'
AND t.id NOT IN (SELECT g.TEAM_ID FROM Games g)
I would like to have a list of all the players in a sports league who are on a team that only has a single member.
Here is the sql:
CREATE TABLE `formsfiles`.`Teams` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(45) NULL ,
PRIMARY KEY (`ID`) );
INSERT INTO `Teams` (`Name`) VALUES ('Sharks');
INSERT INTO `Teams` (`Name`) VALUES ('Jets');
INSERT INTO `Teams` (`Name`) VALUES ('Fish');
INSERT INTO `Teams` (`Name`) VALUES ('Dodgers');
INSERT INTO `Teams` (`Name`) VALUES ('Pigs');
CREATE TABLE `Players` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(45) NULL ,
`Team_ID` INT NULL ,
PRIMARY KEY (`ID`) );
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Jim', '1');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Tom', '1');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Harry', '2');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Dave', '2');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Tim', '3');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Trey', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Jay', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Steve', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Ziggy', '5');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Chris', '4');
The Result should give me:
ID Name
5 Tim
9 Ziggy
Not sure how to get them grouped up?
If you want to return the players on a team with only one member you can use:
select p.id, p.name
from players p
where p.Team_ID in (select Team_ID
from players p
group by Team_ID
having count(Team_ID) = 1);
See SQL Fiddle with Demo
Edit, you can also use (moving from comment):
select max(id) id, max(name) name
from players
group by team_id
having count(team_id) = 1;
See SQL Fiddle with Demo
Thanks Bluefeet:
this work wonderfully:
I want to post it here in case someone serches itin the future:
select max(id) id, max(name) name
from players
group by team_id
having count(team_id) = 1;