How do I join two tables from a database in SQL? - mysql

I'm currently working on a project where we have to join two tables in SQL and then create a page to show the result of the two tables combined.
This is what I have so far:
SELECT *
FROM
ANIMAL
LEFT OUTER JOIN
FOOD_PORTION
ON
ANIMAL = FOOD_PORTION
and then a second page where the outcome should be:
CREATE TABLE ANIMAL(
AnimalID CHAR(5) PRIMARY KEY,
AnimalName CHAR(50) NOT NULL,
Species CHAR(50) NOT NULL,
Weight INT NOT NULL,
DOB DATE NOT NULL,
ExhibitID CHAR(5) REFERENCES EXHIBIT(ExhibitID)
);
CREATE TABLE FOOD_PORTION(
PortionSize INT NOT NULL,
AnimalID CHAR(5) REFERENCES ANIMAL(AnimalID)
);
SELECT C.Name
FROM ANIMAL AS C
UNION
SELECT S.Name
FROM FOOD_PORTION AS S

This should give you what you need. Using tadman's suggestion to change the char column to INT. Also changing the CHAR to VARCHAR columns.
I also made the ID's in each table Identity columns (so they will auto populate).
CREATE TABLE ANIMAL(
AnimalID INT PRIMARY KEY IDENTITY,
AnimalName VARCHAR(50) NOT NULL,
Species VARCHAR(50) NOT NULL,
Weight INT NOT NULL,
DOB DATE NOT NULL,
ExhibitID CHAR(5) REFERENCES EXHIBIT(ExhibitID)
);
CREATE TABLE FOOD_PORTION(
PortionSize INT IDENTITY,
AnimalID INT REFERENCES ANIMAL(AnimalID)
);
SELECT A.*, FP.*
FROM Animal A
INNER JOIN Food_Portion FP ON A.AnimalID = FP.AnimalID

Related

show the names of all suppliers that appear more than once in the supplies table

I have 2 tables supplies and supplier, i need to print names of all suppliers that appear more than once in the supplies table I tried use the follow code:
SELECT name FROM SUPPLIER
WHERE supplier.supplierNum = supplies.supplerNum
having count(supplierNum) > 1;
but the code i=didn't work.
here its the tables:
CREATE TABLE supplies (
supplierNum CHAR(2) NOT NULL,
partNum CHAR(2) NOT NULL,
quantity SMALLINT(6) NOT NULL,
PRIMARY KEY (supplierNum, partNum),
FOREIGN KEY (supplierNum) REFERENCES supplier (supplierNum),
FOREIGN KEY (partNum) REFERENCES parts (partNum)
);
CREATE TABLE supplier (
supplierNum CHAR(2) NOT NULL,
name CHAR(10) NOT NULL,
status TINYINT(4) NOT NULL,
city VARCHAR(10) NOT NULL,
PRIMARY KEY (supplierNum)
);
Count the occurrence in supplies table first then join it with supplier:
SELECT sp.name
FROM supplier AS sp
INNER JOIN
(
SELECT distinct supplierNum
FROM supplies
GROUP BY supplierNum
HAVING COUNT(supplierNum) > 1
) as cnt
ON sp.supplierNum = cnt.supplierNum;
Demo in db<>fiddle here

sql JOIN cause double rows

I have two tables that i need to join them
first table i created using this sql query
CREATE TABLE `users` (
`id` bigint PRIMARY KEY AUTO_INCREMENT,
`user_login` varchar(60),
`user_pass` varchar(255),
`first_name` varchar(30),
`last_name` varchar(30),
`user_status` int(2),
`user_phone_number` varchar(20),
`user_email` varchar(100),
`user_billing_info` text,
`user_temp_units` int(2),
`user_flow_units` int(2),
`user_notes` text
);
second table
CREATE TABLE `station_meta` (
`uid` VARCHAR(25) PRIMARY KEY,
`nickname` varchar(30),
`install_date` date,
`latatude` numeric(10,6),
`longitude` numeric(10,6),
`firmware_ver` varchar(10),
`weir_type` int(2),
`weir_width` numeric,
`dist_to_ground` numeric,
`dist_to_weir` numeric,
`service_fee` numeric,
`notes` text
);
i got double rows when i use this sql query
SELECT * FROM station_meta JOIN users
note: uid is something like 9C9Z454Z5CA in case it need to mention it
so there's not any column that is the same in the other table
UPDATE
Data sample
My results
I'm using it in php function in foreach, so i got double results
Appreciate any help
seems you miss a relation between the two tables ..
if you want avoid cartesian product and retrieve just a matching value between the two table you should add a relation as
table user_station_meta (
`id` bigint PRIMARY KEY AUTO_INCREMENT,
user_id bigint
station_meta_uid VARCHAR(25)
)
once you have inserted the matching values
uid, id
9c2748.. 1
BC8CD4.. 5
you can select single matching result as
select u.*. s.*
from user_station_meta us
JOIN station_meta s on s.uid = us.uid
JOIN users u on u.id = us.id

How do I add data from different tables into one new table in mySQL?

CREATE TABLE CU_ORDER
( cordernumber INT PRIMARY KEY,
fname_lname VARCHAR(50) NOT NULL,
product_name VARCHAR(100) NOT NULL,
);
CREATE TABLE TRACKING_NUMBER
( trnumber INT PRIMARY KEY
);
INSERT INTO CU_ORDER VALUES(456, 'John Doe' , Table);
INSERT INTO TRACKING_NUMBER(276734673);
I am trying to created a table called Package and in the table it will have all the items from cu_order and all the items from tracking_number. How will I add all of the attributes of this table to one table. What am I doing wrong?
CREATE TABLE PACKAGE
( orderno INT PRIMARY KEY,
fname VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
trno INT PRIMARY KEY);
INSERT INTO PACKAGE (........
The two tables do not seem to have a relation, so, presumably, you want a cartesian product of both tables. If so, you can use the insert ... select ... syntax with a cross join:
insert into package(orderno, fname, name, trno)
select
co.cordernumber,
co.fname_lname,
co.product_name,
tn.trnumber
from cu_order co
cross join tracking_number tn
This inserts all possible combinations of rows from both source tables in the target table.
You should also fix the declaration of the package table: yours has two primary keys, which is not allowed. Instead, you probably want a compound primary key made of both columns:
create table package (
orderno int,
fname varchar(50) not null,
name varchar(100) not null,
trno int,
primary key(orderno, trno)
);
You can create a new table from the data of another table (or several tables) by appending a SELECT statement to the CREATE TABLE statement.
However, your two source tables are missing the 1:1 relation allowing this to work, which I assume is the cordernumber of CU_ORDER. It appears the table TRACKING_NUMBER is missing a 'cordernumber' column.
CREATE TABLE TRACKING_NUMBER (
trnumber INT PRIMARY KEY,
cordernumber INT
);
After you added the column 'cordernumber' to TRACKING_NUMBER, you can create the new table PACKAGE with:
CREATE TABLE PACKAGE (
orderno INT PRIMARY KEY,
fname VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
trno INT PRIMARY KEY
)
SELECT
CU_ORDER.cordernumber AS orderno,
CU_ORDER.fname_lname AS fname,
CU_ORDER.product_name AS name,
TRACKING_NUMBER.trnumber AS trno
FROM CU_ORDER, TRACKING_NUMBER
WHERE CU_ORDER.cordernumber=TRACKING_NUMBER.cordernumber;

Correct SQL Multiply across tables

I am at the end of my rope. I am learning SQL for a class. I have tried to get something akin to the to work, but to no avail. Can someone take a look at it.
Keep in mind that I'm new to this. I am trying to get the code to make subtotal equal the sum of column qty multiplied by the sum of column donutPrice in the donut table. I can't find much except for joins and if I do that, I can't use the join as a value.
The ultimate goal is to make it kinda automated.
CREATE TABLE donut
(
donutID int(50) not null auto_increment primary key,
donutName varchar(50) not null,
donutDesc varchar(200),
donutPrice dec(8,2)
);
CREATE TABLE customer
(
customerID int(50) not null auto_increment primary key,
fname char(50) not null,
lname char(50) not null,
address varchar(50) not null,
apartment varchar(10),
city char(50) not null,
state char(2) not null,
zip dec(5) not null,
homeph varchar(10),
mobileph varchar(10),
otherph varchar(10)
);
CREATE TABLE invoice
(
orderID int(50) not null auto_increment primary key,
notes varchar(50) not null,
orderdate date not null,
customerID int(50) not null default 1,
foreign key (customerID) references customer(customerID)
);
CREATE TABLE invoice_line_item
(
donutID int(50) not null,
orderID int(50) not null,
qty dec not null,
subtotal dec(10,2),
subtotal= sum('qty'*'donutPrice') FROM (invoice_line_item, donut),
primary key (donutID, orderID),
foreign key(donutID) references donut(donutID),
foreign key(orderID) references invoice(orderID)
);
ALTER TABLE donut AUTO_INCREMENT=1;
ALTER TABLE customer AUTO_INCREMENT=1001;
ALTER TABLE invoice AUTO_INCREMENT=500;
I guess you want a result looking like this:
OrderID subtotal
1 12.50
2 15.00
27.50
You get that with a query like this:
SELECT invoice.orderID, SUM(invoice_line_item.qty * donut.donutPrice) subtotal
FROM invoice
JOIN invoice_line_item ON invoice.orderID = invoice_line_item.orderID
JOIN donut ON invoice_line_item.donutID = donut.donutID
GROUP BY invoice.orderID WITH ROLLUP
Did you cover entity-relationship data in your class? Your entities are invoice, invoice_line_item, and donut (and your other tables). The relationships between them appear in the ON clauses of the JOIN operations.
Start with a query, and get it working. Then you can create a view ... which is nothing more or less than an encapsulated query.

MYSQL: left Join and sum two tables where one table has two columns referring to the first table

I am trying to create a procedure where my transfer table is joined to my account table. In my transfer table, there are two FK columns that reference the account table id column.
account table:
CREATE TABLE account (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
number VARCHAR(30) NOT NULL DEFAULT '',
description VARCHAR(255)NOT NULL DEFAULT '',
is_active BIT(1) NOT NULL DEFAULT b'1',
PRIMARY KEY (id),
UNIQUE account_name (name, number)
);
transfer table:
CREATE TABLE transfer (
id INT NOT NULL AUTO_INCREMENT,
date DATE NOT NULL,
from_account INT NULL,
to_account INT NULL,
amount DECIMAL(12, 2) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (from_account)
REFERENCES account(id),
FOREIGN KEY (to_account)
REFERENCES account(id)
);
get_account procedure:
CREATE PROCEDURE get_account()
SELECT a.*,
(SUM(t.amount) - SUM(f.amount)) AS balance
FROM account a
LEFT JOIN transfer f
ON a.id = f.from_account
LEFT JOIN transfer t
ON a.id = t.to_account
GROUP BY a.id;
I am trying to subtract the total of the from_accout column from the total of the to_account column. I am able to get the sum of just one column but when I try to get both it returns a NULL.
This seems like it should be easy, but I can't figure it out.