How to select all records with foreign key? - sql

I have tables that have been created like so:
CREATE TABLE `d_account` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`account_name` varchar(128) CHARACTER SET utf8 NOT NULL,
`user_id` smallint(5) NOT NULL,
`type_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_account_type` (`type_id`),
CONSTRAINT `FK_type` FOREIGN KEY (`type_id`) REFERENCES `d_types` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE `d_types` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`id`)
);
How would I select all records that exist in both tables below using the foreign key where the d_type name equals ‘large’?

That's basically just a JOIN like this:
SELECT * FROM d_types t
JOIN d_account a ON t.id = a.type_id
WHERE t.name = 'large';
The * after select should be replaced by the columns you want to select.

Related

How to turn this query into a typeorm query

How do I transform the query below into a typeorm query? I want to return the count of all the jackets inside each column and have it ordered for a specific board.
SELECT c.id, COUNT(j.id)
FROM `column` c, jacket j
WHERE c.boardId = 1 AND j.columnId = c.id
GROUP BY j.columnId
For these tables
CREATE TABLE IF NOT EXISTS `board` (
`id` int(6) unsigned NOT NULL,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `column` (
`id` int(6) unsigned NOT NULL,
`name` varchar(200) NOT NULL,
`boardId` int(6) unsigned NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (boardId) REFERENCES board(`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `jacket` (
`id` int(6) unsigned NOT NULL,
`description` varchar(200) NOT NULL,
`columnId` int(6) unsigned NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (columnId) REFERENCES `column`(`id`)
) DEFAULT CHARSET=utf8;
Figured out a solution.
const results = await this.connection
.createQueryBuilder()
.select('column.id')
.from(Column, 'column')
.addSelect('COUNT(*)', 'jacketCount')
.from(Jacket, 'jacket')
.where('column.boardId = :id', { id: jacketBoardId })
.where('column.id = jacket.columnId')
.groupBy('column.id')
.orderBy('column.position', 'ASC')
.getRawMany();

MariaDB - Foreign Key problem when reference SMALLINT

I have a problem with MariaDB's foreign keys...
These are the tables:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` binary(20) NOT NULL,
`role` smallint(5) unsigned NOT NULL DEFAULT 2,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_UN` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
CREATE TABLE `roles` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `roles_name_UN` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
I can't understand why when I try to update "users" with this command:
ALTER TABLE unito_tweb.users ADD CONSTRAINT users_role_FK FOREIGN KEY (`role`) REFERENCES unito_tweb.roles(id) ON DELETE SET DEFAULT ON UPDATE CASCADE;
I get this error:
Can't create table `unito_tweb`.`users` (errno: 150 "Foreign key constraint is incorrectly formed")

SQL - Can't add new foreign key constraint on SQL Fiddle

I'm working on SQL Fiddle and code so far looks like this:
CREATE TABLE IF NOT EXISTS `orders` (
`id` int(6) unsigned NOT NULL,
`date` DATE NOT NULL,
`customerID` int(6) unsigned NOT NULL,
`paymentAmmount` float(6) unsigned NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_customers_customerID` FOREIGN KEY (`customerID`)
REFERENCES `customers` (`customerID`) );
CREATE TABLE IF NOT EXISTS `items` (
`id` int(6) unsigned NOT NULL,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `customers` (
`customerID` int(6) unsigned NOT NULL,
`firstName` varchar(200) NOT NULL,
`lastName` varchar(200) NOT NULL,
`address` varchar(200) NOT NULL,
#`accountId` int(6) unsigned NOT NULL,
PRIMARY KEY (`customerID`) ) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `items-orders` (
`id` int(6) unsigned NOT NULL,
`itemId` int(6) unsigned NOT NULL,
`orderId` int(6) unsigned NOT NULL,
`itemQuantity` int(1) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_items_itemId` (`itemId`),
CONSTRAINT `FK_items_itemId` FOREIGN KEY (`itemId`) REFERENCES `items` (`id`) ) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `accounts` (
`id` int(6) unsigned NOT NULL,
`email` varchar(200) NOT NULL,
`passwordHash` varchar(200) NOT NULL,
PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8;
There are two lines that don't work:
KEY `FK_customers_customerID` (`customerID`),
CONSTRAINT `FK_customers_customerID` FOREIGN KEY (`customerID`) REFERENCES `customers` (`id`) ) DEFAULT CHARSET=utf8;
I'm trying to link the 'customerID' var in the 'orders' table to the same var in the 'customers' table.
It worked with the 'items-orders' and 'items' table, but now I keep getting this message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'KEY `FK_customers_customerID` (`customerID`), CONSTRAINT `FK_customers_customer' at line 1
I really don't know how to fix this, any help would be appriciated.
The primary key in customers is CustomerId, so you need to use that:
CONSTRAINT `FK_customers_customerID` FOREIGN KEY (`customerID`)
REFERENCES `customers` (`customerID`)

Cannot add or update a child row: a foreign key constraint fails (Clubs and Users)

User Table
CREATE TABLE IF NOT EXISTS `users` (
`userId` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`firstname` varchar(25) NOT NULL,
`lastname` varchar(25) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
`addressLine1` varchar(80) NOT NULL,
`addressLine2` varchar(80) NOT NULL,
`town` varchar(30) NOT NULL,
`county` varchar(30) NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=55 ;
Club Table
CREATE TABLE IF NOT EXISTS `clubs` (
`clubId` int(11) NOT NULL AUTO_INCREMENT,
`clubName` varchar(100) NOT NULL,
`startTime` varchar(5) NOT NULL,
`finishTime` varchar(5) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`clubId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
memberid Table
CREATE TABLE IF NOT EXISTS `membersid` (
`memberId` int(11) NOT NULL AUTO_INCREMENT,
`clubId` int(11) NOT NULL,
`userId` int(11) NOT NULL,
PRIMARY KEY (`memberId`,`clubId`,`userId`),
UNIQUE KEY `memberId` (`memberId`),
KEY `clubId` (`clubId`),
KEY `userId` (`userId`),
KEY `clubId_2` (`clubId`),
KEY `clubId_3` (`clubId`),
KEY `userId_2` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
DAO
String query = "INSERT INTO membersid( userId, clubId ) VALUES ( ?,? )";
Keep getting error Cannot add or update a child row: a foreign key constraint fails
If someone could be that would be great:)
Your keys in the membersid table (please change that name to members) are messed up. Try
CREATE TABLE IF NOT EXISTS members
(
`memberId` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`clubId` int(11) NOT NULL,
`userId` int(11) NOT NULL,
UNIQUE KEY (`clubId`,`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

How to use subqueries in MySQL

I have two tables.
Table user:
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(20) NOT NULL AUTO_INCREMENT,
`ud_id` varchar(50) NOT NULL,
`name` text NOT NULL,
`password` text NOT NULL,
`email` varchar(200) NOT NULL,
`image` varchar(150) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB
and mycatch:
CREATE TABLE IF NOT EXISTS `mycatch` (
`catch_id` int(11) NOT NULL AUTO_INCREMENT,
`catch_name` text NOT NULL,
`catch_details` text NOT NULL,
`longitude` float(10,6) NOT NULL,
`latitude` float(10,6) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`image` varchar(150) NOT NULL,
`user_id` int(20) NOT NULL,
PRIMARY KEY (`catch_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB;
ALTER TABLE `mycatch`
ADD CONSTRAINT `mycatch_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;
My goal is: I want to retrieve longitude and latitude from mycatch against given ud_id (from user) and catch_id (from mycatch) where ud_id = given ud_id and catch_id > given catch_id.
I used the query but fail to retrieve
SELECT ud_id=$ud_id FROM user
WHERE user_id =
(
SELECT user_id,longitude,latitude from mycatch
WHERE catch_id>'$catch_id'
)
The error is:
#1241 - Operand should contain 1 column(s)
First, try not to use subqueries at all, they're very slow in MySQL.
Second, a subquery wouldn't even help here. This is a regular join (no, Mr Singh, not an inner join):
SELECT ud_id FROM user, mycatch
WHERE catch_id>'$catch_id'
AND user.user_id = mycatch.user_id
Select m.longitude,m.latitude from user u left join mycatch m
on u.user_id =m.user_id
where u.ud_id=$ud_id and
m.catch_id >$catch_id