Getting matches from multiple tables in MySQL - mysql

How can i return the matches of two tables.
Table 1:
CREATE TABLE `lost` (
`id` int(11) NOT NULL,
`firstName` int(100) NOT NULL,
`lastName` varchar(100) NOT NULL,
`country` varchar(2) NOT NULL,
`address` varchar(100) NOT NULL,
`email` varchar(120) NOT NULL,
`color` varchar(32) NOT NULL,
`location` varchar(100) NOT NULL,
`airport` int(11) NOT NULL,
`dateReported` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Table 2:
CREATE TABLE `found` (
`id` int(11) NOT NULL,
`firstName` int(100) NOT NULL,
`lastName` varchar(100) NOT NULL,
`country` varchar(2) NOT NULL,
`address` varchar(100) NOT NULL,
`email` varchar(120) NOT NULL,
`color` varchar(32) NOT NULL,
`location` varchar(100) NOT NULL,
`airport` int(11) NOT NULL,
`dateReported` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Now i want to create a query which selects all fields which have any matches on both tables.
And if possible another row which says how many matching fields it has per row.

Not sure I understood, is this what you want?
SELECT t.*,s.*,
(t.firstName = s.firstName ) +
(t.lastName = s.lastName) +
(t.country = s.country) +
(t.address = s.address) +
..... as how_many_matches
FROM `lost` t
JOIN `found` s
ON(t.id = s.id)
MySQL evaluates Boolean expressions as 1 for TRUE and 0 for FALSE , so can you just sum up the comparisons of the columns.
Note that both of your tables are exactly the same, this is not a recommended design. I advise you to add another column TYPE that will save lost / found and combine the two tables .

Related

how to match multiple colums of same table and select maximum match colums

SELECT * FROM `student` as s1
LEFT JOIN `student` as s2 ON s1.mainsubject_id=s2.mainsubject_id WHERE s1.mainsubject_id=s2.mainsubject_id AND s1.mainsubject_id > 0 AND s2.mainsubject_id > 0 GROUP BY s1.id`
i have below student table
CREATE TABLE `student` (
`id` int(10) NOT NULL,
`fname` varchar(100) NOT NULL,
`lname` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`mobile` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`mainsubject_id` varchar(50) NOT NULL,
`subsubject_id` varchar(50) NOT NULL,
`level_id` varchar(50) NOT NULL,
`date` varchar(100) NOT NULL,
`postcode` varchar(50) NOT NULL,
`gender` int(1) NOT NULL,
`deleted` int(10) NOT NULL,
`temppassword` varchar(100) NOT NULL,
`stripe_id` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
i want to get single record of equal or maximum match from 5 colums (mainsubject_id, subsubject_id, level_id, postcode, gender) in same student table.
what is the best way to get record form same table with maximum match form 5 colums

Creating a summary from two tables?

I have two tables and I'm trying to create a summary with the sum of amount due per person but don't have the creative ID involved.
Table 1:
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL,
`Lname` varchar(255) NOT NULL,
`phone` varchar(15) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`city` varchar(255) NOT NULL,
`state` char(2) NOT NULL,
`zip` varchar(50) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`business_name varchar(255) DEFAULT NULL,
Second table:
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`C_ID` INT(10) UNSIGNED NOT NULL,
`Amount_Due` DECIMAL(7 , 2 ) not null DEFAULT 0,
`created_date` DATETIME NOT NULL,
`closed_date` DATETIME default NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
Here is what I'm trying to do:
I'm trying to make a summary with dates within 5/1/18 and 6/15/18.
Have the sum of due amount for each person
Have these aliases : Business name, Phone Number ,Invoiced Amounts
I'm trying to test my code but i'm getting errors:
SELECT Name,phone,SUM(Amount_Due) FROM test_customer,test_invoices
WHERE created_date BETWEEN '2018-05-01' AND "2018-06-15'
If I understand correctly, you need to use JOIN instead of ,(CROSS JOIN) and GROUP BY in non-aggregate function columns.
SELECT Name 'Customer Name',
phone 'Phone number',
SUM(i.Amount_Due) 'Amount due'
FROM test_customer c
INNER JOIN test_invoices i ON C.id = i.C_ID
GROUP BY Name,phone
sqlfiddle

SQL UNION with Where clause a result of the first select

I need to execute the following query:
SELECT (COL1,COL2, ClientID)
FROM Jobs
Union
SELECT (ClientID,COL2,COL3)
FROM Clients WHERE (the ClientID= ClientID my first select)
I'm really stuck, I've been trying joins and unions and have no idea how to do this.
*EDIT*Query to create jobs table
CREATE TABLE IF NOT EXISTS `jobs` (
`JobID` int(11) NOT NULL AUTO_INCREMENT,
`Title` varchar(32) NOT NULL,
`Trade` varchar(32) NOT NULL,
`SubTrade` varchar(300) NOT NULL,
`Urgency` tinyint(4) NOT NULL,
`DatePosted` int(11) NOT NULL,
`Description` varchar(500) NOT NULL,
`Photo` longblob,
`Photo2` longblob,
`Address` varchar(600) NOT NULL,
`ShowAddress` tinyint(4) NOT NULL,
`ShowExact` tinyint(4) NOT NULL,
`JobStatus` tinyint(4) NOT NULL,
`Longitude` double NOT NULL,
`Latitude` double NOT NULL,
`ClientID` int(11) NOT NULL,
`TradesmanID` int(11) DEFAULT NULL,
PRIMARY KEY (`JobID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=171 ;
and query to create clients table is
CREATE TABLE IF NOT EXISTS `clients` (
`ClientID` int(11) NOT NULL AUTO_INCREMENT,
`FName` varchar(32) NOT NULL,
`SName` varchar(32) NOT NULL,
`Email` varchar(32) NOT NULL,
`HomePhone` int(11) NOT NULL,
`Mobile` varchar(30) NOT NULL,
`Address` varchar(100) NOT NULL,
`County` varchar(32) NOT NULL,
`PostCode` varchar(32) NOT NULL,
`UserName` varchar(32) NOT NULL,
`Password` varchar(32) NOT NULL,
`NotificationID` varchar(255) NOT NULL,
PRIMARY KEY (`ClientID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=96 ;
SELECT
Clients.ClientID
,Clients.NotificationID
,Clients.Email
,Clients.Mobile
,Clients.HomePhone
,Jobs.JobID
,Jobs.Title
,Jobs.Trade
,Jobs.Address AS JobAddress
,Jobs.Urgency
,Jobs.DatePosted
,Jobs.Description
,Jobs.Photo
,Jobs.Photo2
,Jobs.ShowAddress
,Jobs.ShowExact
,Jobs.JobStatus
,Jobs.TradesmanID
,Jobs.Longitude
,Jobs.Latitude
FROM
Clients
INNER JOIN
Jobs
on Clients.ClientId = Jobs.ClientId
How about this? There is a bit of duplication i.e. the select clause in the second union replications the first statement but it will work.
SELECT COL1,COL2, ClientID
FROM Jobs
Union
SELECT ClientID,COL2,COL3
FROM Clients WHERE (Select ClientID FROM Jobs)
try this:
SELECT c.ClientID, c.COL2, c.COL3, x.col1
FROM Clients c inner join
(select clientId,
min(col1) as col1
from jobs
group by clientId) x
on c.clientId = x.clientId

How to include another table in JOIN

Below is my mysql query
SELECT
opensalesorder.so_number,
items.VendorName,
opensalesorder.item_number,
items_custom_fields.FieldValue AS `Stock Item`,
vendor_custom_fields.FieldValue AS `Paid Freight Allowance`,
items.QuantityOnHand,
items.ReorderPoint,
items.MaxQty,
SUM(opensalesorder.quantity_on_order),
items.PurchaseCost,
items.VendorName,
items.VendorName,
items.PurchaseCost,
opensalesorder.status,
items.ItemType
FROM
vendor,
`opensalesorder`
inner join items
on opensalesorder.item_number = items.ItemName
JOIN items_custom_fields
ON items_custom_fields.ItemName = items.ItemName
JOIN vendor_custom_fields
ON vendor_custom_fields.VName = vendor.VName
WHERE opensalesorder.item_number = items.ItemName
and items_custom_fields.FieldName ='Stock Item'
and vendor_custom_fields.FieldName ='Paid Freight Allowance'
and opensalesorder.status NOT LIKE 'on po'
AND opensalesorder.so_number NOT IN ('2','3')
AND items.VendorName NOT IN ('Access')
AND opensalesorder.item_number NOT IN ('018-0001')
group by opensalesorder.item_number
LIMIT 100
on executing this query I am getting error like
#1054 - Unknown column 'vendor.VName' in 'on clause'
But I have included the vendor table in FROM clause.
Is this right way to include a table in JOIN ?
So whats wrong is with this query ?
EDIT:
SHOW CREATE TABLE FOR opensalesorder
CREATE TABLE `opensalesorder` (
`so_number` decimal(10,0) NOT NULL,
`item_number` varchar(20) NOT NULL,
`quantity_on_order` int(11) NOT NULL,
`quantity_to_order` int(11) NOT NULL,
`status` varchar(20) NOT NULL,
`editsequence` text NOT NULL,
`TxnLineID` text NOT NULL,
`TxnID` text NOT NULL,
`dateCreated` date NOT NULL,
`shipDate` date NOT NULL,
`customer` text NOT NULL,
`itemclass` text NOT NULL,
UNIQUE KEY `unique_mapping` (`so_number`,`item_number`),
KEY `so_number` (`so_number`),
KEY `item_number` (`item_number`),
KEY `status` (`status`)
)
SHOW CREATE TABLE FOR items
CREATE TABLE `items` (
`ItemName` varchar(30) NOT NULL,
`VendorName` varchar(40) DEFAULT NULL,
`QuantityOnHand` int(11) DEFAULT NULL,
`QuantityOnSalesOrder` int(11) DEFAULT NULL,
`ReorderPoint` int(11) DEFAULT NULL,
`PurchaseCost` double DEFAULT NULL,
`AverageCost` double DEFAULT NULL,
`SalesPrice` double DEFAULT NULL,
`PurchaseDesc` varchar(200) DEFAULT NULL,
`SalesDesc` varchar(200) DEFAULT NULL,
`ItemType` varchar(30) DEFAULT NULL,
`FreeCode` int(11) DEFAULT NULL,
`SubGroup` varchar(10) DEFAULT NULL,
`DateNewItem` date DEFAULT NULL,
`Notes` text,
`MaxQty` int(11) DEFAULT NULL,
`QuantityOnPO` int(11) DEFAULT NULL,
PRIMARY KEY (`ItemName`),
KEY `ItemName` (`ItemName`),
KEY `VendorName` (`VendorName`)
)
SHOW CREATE TABLE FOR vendor_custom_fields
CREATE TABLE `vendor_custom_fields` (
`VName` text NOT NULL,
`FieldName` text NOT NULL,
`FieldValue` text NOT NULL,
`FieldType` text NOT NULL,
PRIMARY KEY (`VName`(120),`FieldName`(120)),
FULLTEXT KEY `VName_index` (`VName`)
)
SHOW CREATE TABLE FOR vendor
CREATE TABLE `vendor` (
`VName` varchar(60) NOT NULL,
`CompanyName` varchar(100) NOT NULL,
`Address1` varchar(120) NOT NULL,
`Address2` varchar(120) NOT NULL,
`City` varchar(40) NOT NULL,
`State` varchar(50) NOT NULL,
`PostalCode` varchar(13) NOT NULL,
`Phone` varchar(13) NOT NULL,
`Fax` varchar(13) NOT NULL,
`AlternatePhone` varchar(13) NOT NULL,
`AlternateContact` varchar(30) NOT NULL,
`Email` varchar(40) NOT NULL,
`AccountNumber` varchar(30) NOT NULL,
`Balance` double NOT NULL,
`RepEmail` varchar(40) NOT NULL,
`FreightAllowance` double DEFAULT NULL,
`MinimumPOLimit` double DEFAULT NULL,
`Notes` text NOT NULL,
PRIMARY KEY (`VName`)
)
I think the problem is mixing the implied join with the (unimplied) 'stated' joins. When I put 'vendor' in as a regular join the query was fine.
(I had to comment out references to 'items_custom_fields' as you didn't include the table definition)
Here's a fiddle.

sql statement mysql notcorrect

SELECT SUBSTRING(m.own,3,4) as c , (select amphur.AMPHUR_NAME where c = SUBSTRING(m.own,3,4) ),
COUNT(* ) AS cnt
FROM MEMBER AS m
GROUP BY SUBSTRING(m.own,3,4)
order by cnt desc
sql statement mysql
what wrong with code below when i fill
(select amphur.AMPHUR_NAME where c = SUBSTRING(m.own,3,4) )
it error
CREATE TABLE IF NOT EXISTS `member` (
`idmember` int(11) NOT NULL AUTO_INCREMENT,
`own` varchar(255) DEFAULT NULL,
`Sname` varchar(255) DEFAULT NULL,
`Ssurname` varchar(255) DEFAULT NULL,
`Sex` enum('¿','¿') NOT NULL,
`Hno` varchar(255) DEFAULT NULL,
`Moo` varchar(255) DEFAULT NULL,
`tambol` varchar(200) NOT NULL,
`dateofbirth` date DEFAULT NULL,
`migratedate` date DEFAULT NULL,
`status` enum('5','4','3','2','1') DEFAULT '5',
`Unit` int(4) DEFAULT NULL,
`staff1` int(11) DEFAULT NULL,
`staff2` int(11) DEFAULT NULL,
`fathercode` varchar(30) NOT NULL,
`mathercode` varchar(30) NOT NULL,
PRIMARY KEY (`idmember`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=8994 ;
CREATE TABLE IF NOT EXISTS `amphur` (
`AMPHUR_ID` int(5) NOT NULL AUTO_INCREMENT,
`AMPHUR_CODE` varchar(4) COLLATE utf8_unicode_ci NOT NULL,
`AMPHUR_NAME` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
`GEO_ID` int(5) NOT NULL DEFAULT '0',
`PROVINCE_ID` int(5) NOT NULL DEFAULT '0',
`province_name` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`AMPHUR_ID`),
KEY `province_name` (`province_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=999 ;
Your subquery is missing a From clause:
SELECT SUBSTRING(m.own,3,4) as c
, (select amphur.AMPHUR_NAME
From amphur
Where ??? = SUBSTRING(m.own,3,4) )
, COUNT(* ) AS cnt
FROM MEMBER AS m
However, how does the amphur table relate to the member table?
You cannot use aliases in the same level.
Even if you could, you are filtering on non-correlated columns in your subquery: the subquery would just return the record from amphur if there is one record, or an error if there are more.
Could you please provide some sample data and the desired recordset?
there is no "FROM" clause in your select Amphur.amphur_name