I'm trying to select mltiple rows from tow table :
first table is donor
CREATE TABLE donor(
donor_number INT NOT NULL AUTO_INCREMENT,
d_name VARCHAR(30) NOT NULL,
mobile_number INT NOT NULL,
blood_group VARCHAR(20) NULL,
dob DATE NOT NULL,
gender ENUM('male','female') NOT NULL,
govid INT(10) NOT NULL,
PRIMARY KEY (donor_number )
);
second table is blood_donation
CREATE TABLE blood_donation(
donor_number INT NOT NULL,
date_of_donate DATE NOT NULL,
blood_group VARCHAR(20) NULL,
serial_number INT(10) NOT NULL,
blood_component ENUM('wb','prcb') NOT NULL,
PRIMARY KEY (donor_number , date_of_donate ),
FOREIGN KEY (donor_number) REFERENCES donor(donor_number)
);
with this select statement:
SELECT
serial_number,
blood_group
FROM blood_donation
WHERE date_of_donate = '2012-07-18'
UNION ALL
SELECT
blood_group
FROM donor
WHERE donor.donor_number=blood_donation.donor_number;
but, I get error
SQL state 42S22: Unknown column 'blood_donation.donor_number' in 'where clause'
any idea????
Actually you should not be using UNION but JOIN :)
you query will look like this
SELECT
blood_donation.serial_number,
donor.blood_group
FROM
blood_donation ,
donor
WHERE donor.donor_number = blood_donation.donor_number AND date_of_donate = '2012-07-18' ;
A UNION is used to combine more than one result set into a single result set - and each result set must have the same set of columns.
What you need is a JOIN, which is how you link multiple tables together on foreign keys etc and would be something like this:
SELECT
serial_number,
blood_group
FROM blood_donation
INNER JOIN donor ON donor.donor_number=blood_donation.donor_number
WHERE date_of_donate = '2012-07-18'
SELECT
dd.serial_number,
dd.blood_group
FROM blood_donation dd
inner join
donor d
on d.donor_number=dd.donor_number
WHERE dd.date_of_donate = '2012-07-18';
UNION is not what exactly you need, Read some more about JOINS. Also please change the selection alias of columns as per the need. And you can use Left Join instead of Inner Join if you don't want a mandatory join condition on tables.
Related
I created two tables using MYSQL, tblorder and tblitem.
CREATE TABLE `tblorder` (
`orderId` int NOT NULL,
`orderName` varchar(45) NOT NULL,
PRIMARY KEY (`orderId`)
CREATE TABLE `tblitem` (
`itemId` int NOT NULL,
`itemName` varchar(45) NOT NULL,
`itemUnit` varchar(5) NOT NULL,
`itemRate` double NOT NULL,
`orderRef` int NOT NULL,
PRIMARY KEY (`itemId`),
KEY `fk1_idx` (`orderRef`),
CONSTRAINT `fk1` FOREIGN KEY (`orderRef`) REFERENCES `tblorder` (`orderId`)
I tried to join the two tables using query below
SELECT orderId,orderName, itemName, itemUnit,itemRate
FROM tblitem
INNER JOIN tblorder on tblorder.orderId = tblitem.orderRef
Now result show like Image-01
How to remove duplicate values in orderId ,OrderName columns in result table?
Thanks to help me to solve this problem.
After joining tables is it possible to get output like below?
Answer for this question is available in below link. https://dba.stackexchange.com/questions/287746/join-two-tables-in-mysql-and-avoid-duplicate-values
SELECT CASE WHEN sortId = 1 THEN CAST(orderId AS CHAR(10)) ELSE '' END AS
orderId, CASE WHEN sortId = 1 THEN orderName ELSE '' END AS orderName,
itemName, itemUnit, itemRate
FROM
(
SELECT orderId, orderName, itemName, itemUnit, itemRate, ROW_NUMBER() OVER
(PARTITION BY orderId ORDER BY itemId) AS sortId
FROM
(
SELECT orderId, orderName, itemName, itemUnit, itemRate, itemId
FROM tblitem
INNER JOIN tblorder
on tblorder.orderId = tblitem.orderRef
) orderItems
) orderItemsSorted
ORDER BY orderItemsSorted.orderId, orderItemsSorted.sortId
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
I've been stuck on a MySQL query. The table is:
CREATE TABLE items_costs (
UPC varchar(15) NOT NULL,
SupplierID int(11) NOT NULL,
Current_as_of_Date datetime DEFAULT NULL,
Cost1 float DEFAULT NULL,
Cost2 float DEFAULT NULL,
Cost3 float DEFAULT NULL,
MSRP float DEFAULT NULL,
MAP float DEFAULT NULL,
Unique_Entry_Id datetime DEFAULT NULL,
PRIMARY KEY (UPC,SupplierID),
KEY SupplierID (SupplierID),
CONSTRAINT items_costs_ibfk_1 FOREIGN KEY (UPC) REFERENCES items (UPC),
CONSTRAINT items_costs_ibfk_2 FOREIGN KEY (SupplierID) REFERENCES suppliers (SupplierID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8`
I'm getting the lowest of Cost1, Cost2, Cost3 for each item:
MIN(LEAST(IFNULL(ic.Cost3, ic.Cost1), IFNULL(ic.Cost2, ic.Cost1), ic.Cost1)) AS Cost
However, now I need to get the SupplierID associated with that particular Cost
I've tried:
SELECT
ic.UPC,
ic.SupplierID,
ic.Current_as_of_Date,
ic.Cost1 AS Cost,
ic.MSRP,
ic.MAP,
s.SupplierName,
s.Map_YN AS Supplier_MAP
FROM
items_costs AS ic
JOIN
suppliers AS s ON s.supplierId = ic.SupplierID
WHERE
(ic.upc , ic.Cost1) IN (SELECT
ic_min.UPC,
MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
IFNULL(ic_min.Cost2, ic_min.Cost1),
ic_min.Cost1)) AS Cost
FROM
items_costs ic_min
GROUP BY ic_min.UPC))
...which gives the lowest Cost by UPC, as recommended in other threads. However, still getting duplicate UPC's, which should be unique.
What could I be doing wrong here?
Thanks a lot!
You could use DISTINCT
SELECT DISTINCT
ic.UPC,
ic.SupplierID,
ic.Current_as_of_Date,
ic.Cost1 AS Cost,
ic.MSRP,
ic.MAP,
s.SupplierName,
s.Map_YN AS Supplier_MAP
FROM items_costs AS ic
JOIN suppliers AS s ON s.supplierId = ic.SupplierID
WHERE (ic.upc , ic.Cost1) IN (
SELECT
ic_min.UPC,
MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
IFNULL(ic_min.Cost2, ic_min.Cost1),
ic_min.Cost1)) AS Cost
FROM items_costs ic_min
GROUP BY ic_min.UPC))
Thanks for your help!
I found the answer here, and it seems to be a common question: https://dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html
SELECT
ic1.upc,
ic1.supplierid,
ic1.MSRP,
ic1.MAP,
ROUND((LEAST(IFNULL(ic1.Cost3, ic1.Cost1),
IFNULL(ic1.Cost2, ic1.Cost1),
ic1.Cost1)),
2) AS Cost,
s.SupplierName,
s.Map_YN AS Supplier_MAP
FROM
items_costs AS ic1
JOIN
suppliers AS s ON s.supplierid = ic1.supplierid
WHERE
ic1.cost1 = (SELECT
MIN(ic2.cost1)
FROM
items_costs AS ic2
WHERE
ic1.upc = ic2.upc)
I have a table that contains many informations:
CREATE TABLE sequences (
`id` INT(11) NOT NULL DEFAULT '0',
`name` TEXT NULL,enter code here
`nbrlsu` BIGINT(20) NULL DEFAULT NULL,
`nbrits` BIGINT(20) NULL DEFAULT NULL,
`nbrco1` BIGINT(20) NULL DEFAULT NULL,
`nbrrcbl` BIGINT(20) NULL DEFAULT NULL,
`nbrmatk` BIGINT(20) NULL DEFAULT NULL,
`nbrsequences` BIGINT(20) NULL DEFAULT NULL,
`parent_id` BIGINT(20) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
I want to create a table based on sum of columns in the first table
for exemple I want to know te number of elements that have the same parent_id and has numbersequences>0
and I want to know for each type of sequences the number of rows that contains information:
SELECT parent_id ,
Classification,count(id) as nbrspecies,
SUM(nbrsequences) ,
SUM(nbrco1),
SUM(nbrits),
SUM(nbrlsu),
SUM(nbrrcbl),
SUM(nbrmatk)
FROM dashboard_specimen
GROUP BY parent_id
and I have an other kind of queries:
SELECT parent_id ,
count(id) as co1
FROM dashboard_specimen
WHERE nbrco1>0
GROUP BY parent_id ;
and
SELECT parent_id ,
count(id) as nbrspecies
FROM dashboard_specimen
WHERE nbrsequences>0
GROUP BY parent_id
and other types like this
and my goal in the end is to insert this information into an other table with insert select
like this:
INSERT INTO bold_namestats (id,
name,
numberofstrains,
numberofsequences,
numberofco1,
numberofits,
numberoflsu,
numberofrbcl,
numberofmatk)
SELECT parent_id ,
Classification,
count(id) as nbrspecies,
SUM(nbrsequences) ,
SUM(nbrco1),
SUM(nbrits),
SUM(nbrlsu),
SUM(nbrrcbl),
SUM(nbrmatk)
FROM dashboard_specimen
GROUP BY parent_id
I don't know if there is a simple way to do this with temp tables or something like this
If I understand well, you could do a subquery for each column you want to populate, filtering each subquery for an id.
INSERT INTO bold_namestats (id,
name,
numberofstrains,
numberofsequences,
numberofco1,
numberofits,
numberoflsu,
numberofrbcl,
numberofmatk)
select parent_id, (*select1* where parent_id=...), (*select2* where parent_id=...), ... , (*selectn* where parent_id=...)
from dashboard_specimen
group by parent_id
where select1, select2, ... , selectn are the different queries you have.
Finally I have resolved my problem using join and temp tables
INSERT INTO bold_namestats (_id,numberofstrains, numberofsequences,numberofco1,numberofits,numberoflsu,numberofrbcl,numberofmatk,numberstrainswithco1,numberstrainswithseq)
SELECT a._id ,a.numberofstrains,a.numberofsequences ,a.numberofco1,a.numberofits,a.numberoflsu,a.numberofrbcl,a.numberofmatk,b.numberofstrainswithco1,c.numberofstrainswithseq FROM bold_temp_namestats a left join bold_strainswithco1 b on a._id=b.parent_id left join bold_strainswithseq c on a._id=c.parent_id union
SELECT a._id ,a.numberofstrains,a.numberofsequences ,a.numberofco1,a.numberofits,a.numberoflsu,a.numberofrbcl,a.numberofmatk,b.numberofstrainswithco1,c.numberofstrainswithseq FROM bold_temp_namestats a right join bold_strainswithco1 b on a._id=b.parent_id left join bold_strainswithseq c on a._id=c.parent_id ;
this query is used to replace full outer join so I fill 3 tables with data and after that I insert with joinin result with left and right join and union the result to get full lines in the end
I keep getting a Unknown column 'makeId' in 'field list' when I used the INSERT to take info from tables and put it in the vehicleNormal.
INSERT INTO vehicleNormal (makeId, modelId, year, cylinders, driveId, mpgHighway, mpgCity, fueltypeId)
(SELECT makeId, modelId, year, cylinders, driveId, mpgH, mpgC, fueltypeId
FROM vehicle
JOIN vehicleMake ON vehicle.make = vehicleMake.make
JOIN vehicleModel ON vehicle.model = vehicleModel.model
JOIN vehicleDrive ON vehicle.drive = vehicleDrive.drive
JOIN vehicleFuelType ON vehicle.fueltype = vehicleFuelType.fueltype);
When my table has the 'makeId'...
CREATE TABLE ‘vehicleNormal’ (
‘vehicleId’ INT NOT NULL AUTO_INCREMENT,
‘fuelType’ VARCHAR (255) DEFAULT NULL,
‘makeId’ INT (11) DEFAULT NULL,
‘modelId’ INT (11) DEFAULT NULL,
‘year’ INT (11) DEFAULT NULL,
‘cylinders’ INT (11) DEFAULT NULL,
‘driveId’ INT (11) DEFAULT NULL,
‘mpgHighway’ DECIMAL(10,2),
PRIMARY KEY (‘vehicleId’)
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
Any help would be great. :/
Just added the vehicle. to all the columns in SELECT. Thank you Gordon Linoff for pointing me in the right direction.
INSERT INTO vehicleNormal (makeId, modelId, year, cylinders, driveId, mpgHighway, mpgCity, fueltypeId)
(SELECT vehicle.make, vehicle.model, vehicle.year, vehicle.cylinders, vehicle.drive, vehicle.mpgHighway, vehicle.mpgCity, vehicle.fueltype
FROM vehicle
JOIN vehicleMake ON vehicle.make = vehicleMake.make
JOIN vehicleModel ON vehicle.model = vehicleModel.model
JOIN vehicleDrive ON vehicle.drive = vehicleDrive.drive
JOIN vehicleFuelType ON vehicle.fueltype = vehicleFuelType.fueltype);
You have provided the table definition for the destination table in the INSERT, but not for the source tables. The SELECT will generate the error if a field called makeId does not exist in the source tables.